我想在一个数字的千位上加一个逗号。
String.Format()是正确的路径吗?我应该使用什么格式?
我想在一个数字的千位上加一个逗号。
String.Format()是正确的路径吗?我应该使用什么格式?
当前回答
$"{1234:n}"; // Output: 1,234.00
$"{1234:n0}"; // No digits after the decimal point. Output: 9,876
其他回答
请注意,您正在格式化的值应该是数字。 它看起来不像会接受数字的字符串表示,格式是逗号。
试试这个:
var number = 123456789;
var str = number.ToString("N0");
结果是:“123,456,789”
String.Format("{0:#,###,###.##}", MyNumber)
这将在相关点处给出逗号。
如果你想要特定文化,你可能想试试这个:
使用命名空间:"using System.Globalization;"
(19950000.0)。ToString("N",new CultureInfo("en-US")) = 19,950,000.00
(19950000.0)。ToString("N",new CultureInfo("is-IS")) = 19.950.000,00
印度文化: (19950000.0)。ToString("N",new CultureInfo("hi-IN"))= 1,99,50,000.00
注意:一些区域性使用,表示小数而不是。所以要小心。
投票最多的答案很好,7年来一直很有帮助。随着c# 6.0的引入,特别是字符串插值,有了一种更整洁,在我看来更安全的方法来完成要求在数字的千位处添加逗号:
var i = 5222000;
var s = $"{i:n} is the number"; // results to > 5,222,000.00 is the number
s = $"{i:n0} has no decimal"; // results to > 5,222,000 has no decimal
其中变量i被放置在占位符(即{0})的位置。所以不需要记住哪个物体到哪个位置。格式(即:n)没有改变。要了解最新的完整功能,您可以访问这个页面。