如何使用逗号格式化数字?

50
int a = 10000000;
a.ToString();

如何生成输出?

10,000,000


6个回答

89

尝试使用N0以去除小数部分:

string formatted = a.ToString("N0"); // 10,000,000

有没有办法使用a.ToString("#");来实现这个?在我的情况下,我需要值为零时为空白,但我也需要逗号 - 或者我应该像a.ToString("#,###,###,###,###,###,###")这样做吗? - James
你可能需要使用 if{}else{} 块来处理0。 - Steve Woods
@cms 如何实现这个 **10,24,78,000**。 - Meer

12

你也可以使用String.Format:

int x = 100000;
string y = string.Empty;
y = string.Format("{0:#,##0.##}", x); 
//Will output: 100,000
如果您有十进制数,则相同的代码将输出2位小数:
double x = 100000.2333;
string y = string.Empty;
y = string.Format("{0:#,##0.##}", x); 
//Will output: 100,000.23

要将逗号代替小数点,请使用以下内容:

double x = 100000.2333;
string y = string.Empty;
y = string.Format(System.Globalization.CultureInfo.GetCultureInfo("de-DE"), "{0:#,##0.##}", x);

如果小数点分隔符是逗号呢? - Emil

10

2

更简单的String.Format选项:

int a = 10000000;
String.Format("{0:n0}", a); //10,000,000

1

对于C#6或更高版本,甚至更简单:

string formatted = $"{a:N0}";

为了方便大家查找,这里提供一个链接:https://learn.microsoft.com/en-us/dotnet/standard/base-types/composite-formatting?redirectedfrom=MSDN - Jacksonkr

-3

a.tostring("00,000,000")


我认为你字面理解了 // 符号。我认为 OP 的意思是将其作为注释代码编写。 - bendewey
6
你可以尝试将 a 设为 "10,000,000" ;) - johnc

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接