显示最多3个字符的数字

时间:2016-03-06 12:33:47

标签: c# unityscript number-formatting

我的号码范围为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('.', ',');
}

1 个答案:

答案 0 :(得分: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));