我有一个标签来显示一个无符号整数,它有一个最大长度。我想格式化要显示的数字:
1 = "1"
1000 = "1,000"
12400 = "12.4k"
101,800,000 = "102M" // !!!
1,849,000 = "1.85M"
所以,我最终得到了一个最大长度为 5 的字符串。
我的范围是从 0 到 199,999,999。
有没有一种方法可以在不处理很多情况(即很多间隔)的情况下做到这一点?
最佳答案
我可能来不及了,但这里有一个扩展方法,它返回您想要的格式的数字:
public static string ToShortString(this int n)
{
if (n >= 1e8)
{
return (Math.Round((double)n / 1e6, 0)).ToString() + "M";
}
else if (n >= 1e7)
{
return (Math.Round((double)n / 1e6, 1)).ToString() + "M";
}
else if (n >= 1e6)
{
return (Math.Round((double)n / 1e6, 2)).ToString() + "M";
}
else if (n >= 1e5)
{
return (Math.Round((double)n / 1e3, 0)).ToString() + "K";
}
else if (n >= 1e4)
{
return (Math.Round((double)n / 1e3, 1)).ToString() + "K";
}
else if (n >= 1e3)
{
return n.ToString("##,#");
}
else
{
return n.ToString();
}
}
测试:
Console.WriteLine((5).ToShortString()); // displays 5
Console.WriteLine((55).ToShortString()); // displays 55
Console.WriteLine((555).ToShortString()); // displays 555
Console.WriteLine((5555).ToShortString()); // displays 5,555
Console.WriteLine((55555).ToShortString()); // displays 55.6K
Console.WriteLine((555555).ToShortString()); // displays 556K
Console.WriteLine((5555555).ToShortString()); // displays 5.56M
Console.WriteLine((55555555).ToShortString()); // displays 55.6M
Console.WriteLine((555555555).ToShortString()); // displays 556M
关于c# - 如何格式化数字以具有相同的位数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11971110/