Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String.Format - integer, thousands separator, no decimal

what is the simplest String.Format template to format an integer with a thousands separator (comma) and no decimal places? en-US culture. Examples of desired formatting:

1200 = 1,200

900 = 900

8 = 8

thanks!

like image 271
mdelvecchio Avatar asked Mar 19 '23 04:03

mdelvecchio


2 Answers

N0 is the format you are looking for. N will format it with commas, and the 0 is to tell it to not use decimals:

// will format as 33,540
string.Format("{0:N0}", 33540.54M)

// example using an integer: 1,200
string.Format("{0:N0}", 1200);

From MSDN:

Result: Integral and decimal digits, group separators, and a decimal separator with optional negative sign. Supported by: All numeric types. Precision specifier: Desired number of decimal places. Default precision specifier: Defined byNumberFormatInfo.NumberDecimalDigits. More information: The Numeric ("N") Format Specifier.

like image 157
Dismissile Avatar answered Mar 21 '23 17:03

Dismissile


That's not possible to do using only a format string. You also have to specify the culture or number format, or make sure that the current culture is the right one. The thousands separator uses the separator specified in the culture, you can't specify the separator in the format.

The format string N0 is the shortest to get thousands separator and zero decimal places.

Example:

String.Format(CultureInfo.GetCultureInfo("en-US"), "{0:N0}", 12345678.901234)
like image 30
Guffa Avatar answered Mar 21 '23 17:03

Guffa