0

Using the below code I am formatting the double number with group seperator like if the number is 5000, it should display like 5,000 and if the number is only 5 it should display only 5 but here its displaying 05 how can I avoid this?

double doubleNumTest = 5;
string str = doubleNumTest.ToString("0,0", CultureInfo.InvariantCulture);
Mohamad Shiralizadeh
  • 8,329
  • 6
  • 58
  • 93
user1133737
  • 113
  • 5
  • 22

4 Answers4

1

You can use the numeric format specifier with zero fractional digits; N0:

string str = doubleNumTest.ToString("N0", CultureInfo.InvariantCulture);
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
0

Try this:

string str = doubleNumTest.ToString("#,0", CultureInfo.InvariantCulture);
dario
  • 5,149
  • 12
  • 28
  • 32
0

The format string that you are using is telling it to print the leading zero's, try using the # instead of the 0.

from MSDN

"0" Zero placeholder Replaces the zero with the corresponding digit if one is present; otherwise, zero appears in the result string.

"#" Digit placeholder Replaces the "#" symbol with the corresponding digit if one is present; otherwise, no digit appears in the result string.

Community
  • 1
  • 1
Mark Hall
  • 53,938
  • 9
  • 94
  • 111
0

Use Digit placeholder:

Replaces the "#" symbol with the corresponding digit if one is present; otherwise, no digit appears in the result string.

More information: The "#" Custom Specifier.

double doubleNumTest = 5;
string str = doubleNumTest.ToString("#,#", CultureInfo.InvariantCulture);

double doubleNumTest = 500;
string str = doubleNumTest.ToString("#,#", CultureInfo.InvariantCulture);

double doubleNumTest = 50000;
string str = doubleNumTest.ToString("#,#", CultureInfo.InvariantCulture);

Output:

5
500
50,000

See here for the custom numeric formats that can be passed to this method.

Mohamad Shiralizadeh
  • 8,329
  • 6
  • 58
  • 93