如何用逗号格式化数字?

24 c# numbers tostring

int a = 10000000;
a.ToString();
Run Code Online (Sandbox Code Playgroud)

我该如何输出?

10,000,000

CMS*_*CMS 43

尝试N0没有小数部分:

string formatted = a.ToString("N0"); // 10,000,000
Run Code Online (Sandbox Code Playgroud)


Wil*_* Jr 8

你也可以做String.Format:

int x = 100000;
string y = string.Empty;
y = string.Format("{0:#,##0.##}", x); 
//Will output: 100,000
Run Code Online (Sandbox Code Playgroud)

如果你有小数,相同的代码将输出2位小数:

double x = 100000.2333;
string y = string.Empty;
y = string.Format("{0:#,##0.##}", x); 
//Will output: 100,000.23
Run Code Online (Sandbox Code Playgroud)

要使用逗号而不是十进制使用此:

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


lc.*_*lc. 7

a.ToString("N0")

另请参阅:MSDN中的标准数字格式字符串