【问题标题】:Display max 3 characters of number最多显示 3 个字符的数字
【发布时间】:2016-03-06 12:33:46
【问题描述】:

我有一个从1999 的号码。

我希望 1<10 显示单个小数(如果有效)。但是10999 任何时候都不应该显示小数:

float[] testNums = { 2f, 3.4f, 7.59f, 22f, 37.3f, 104f, 351.7f };

string[] output = new string[testNums.Length];
for (int i = 0; i < testNums.Length; i++) {
    string strNum = testNums[i].ToString("0.#"); //"0.#" is the closest I've found
    output [i] = strNum;
}
Debug.Log(string.Join(", ", output));

结果:2, 3.4, 7.6, 22, 37.7, 104, 351.7

想要的结果:2, 3.4, 7.6, 22, 37, 104, 351

有没有办法只使用number formats 来实现这一点,还是我必须为它编写代码? (例如:)

if(strNum.Length >= 4)
{
    strNum = strNum.Substring(0,3).TrimEnd('.', ',');
}

【问题讨论】:

    标签: c# unityscript number-formatting


    【解决方案1】:

    没有取决于值的有条件的数字格式(我知道),因此必须在代码中完成。您当然可以根据值在代码中自己更改格式。例如:

    float[] testNums = { 2f, 3.4f, 7.59f, 22f, 37.3f, 104f, 351.7f };
    
    string[] output = new string[testNums.Length];
    
    string lowValueFormat = "0.#";
    
    for (int i = 0; i < testNums.Length; i++)
    {
        string strNum;
        if (testNums[i] < 10)
        {
            strNum = testNums[i].ToString(lowValueFormat);
        }
        else
        {
            strNum = Math.Floor(testNums[i]).ToString();
        }
        output[i] = strNum;
    }
    Debug.Log(string.Join(", ", output));
    

    【讨论】:

    • 可以是.ToString()而不是.ToString(highValueFormat)
    • @Sakura:没错,因为我们使用的是“Math.Floor()”,所以高价值的格式就变得多余了。更新答案
    • 哈哈 :D 既然你删除了highValueFormat,那么定义lowValueFormat是多余的
    • @Sakura:实际上它已经是多余的,因为我们使用了“Math.Floor()”。但是考虑到答案表明我们根据值更改格式,它仍然与答案相关。因为这仍然是我们在这里所做的。我是否可以建议您提供一个排除格式部分的您自己的答案,以澄清更改格式可能是多余的?
    • (short)testNums[i] 呢?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-19
    • 2019-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-20
    相关资源
    最近更新 更多