我想在一个数字的千位上加一个逗号。
String.Format()是正确的路径吗?我应该使用什么格式?
我想在一个数字的千位上加一个逗号。
String.Format()是正确的路径吗?我应该使用什么格式?
当前回答
c# 7.1(也许更早?)通过字符串插值使这变得简单而美观:
var jackpot = 1_000_000; // underscore separators in numeric literals also available since C# 7.0
var niceNumberString = $"Jackpot is {jackpot:n}";
var niceMoneyString = $"Jackpot is {jackpot:C}";
其他回答
$"{1234:n}"; // Output: 1,234.00
$"{1234:n0}"; // No digits after the decimal point. Output: 9,876
String.Format("{0:#,###,###.##}", MyNumber)
这将在相关点处给出逗号。
我尝试了上面的许多建议,但下面的建议更适合我:
string.Format("{0:##,###.00}", myValue)
但是当你有像0.2014这样的值时,它会失败,因为我使用。21
string.Format("{0:#,##0.00}", myValue)
更简单,使用字符串插值代替字符串。格式
$"{12456:n0}"; // 12,456
$"{12456:n2}"; // 12,456.00
或者使用yourVariable
double yourVariable = 12456.0;
$"{yourVariable:n0}";
$"{yourVariable:n2}";
String.Format("0,###.###"); also works with decimal places