C # + Formatting Strings

I feel like I am trying to do something simple, but I am not getting the result I want. I want to display a base number that will always be positive. I don't want any leading zeros, but I need thousands separators. For example, for the following inputs, I need the following outputs:

3 -> 3
30 -> 30
300 -> 300
3000 -> 3,000
30000 -> 30,000
300000 -> 300,000 

      

I am currently using the following formatting code when trying to do this:

  string text = "*Based on " + String.Format("{0:0,0}", total) + " entries";

      

Currently the output looks like this:

3 -> 03
3000 -> 3,000

      

You can see how a leading "0" is added when the thousands separator is not needed. How do I format my numbers correctly?

thanks

+2


a source to share


6 answers


string.Format(new CultureInfo("en-US"), "{0:N0}", total)

      

See: Standard Number Format Strings

- or -



string.Format(new CultureInfo("en-US"), "{0:#,#}", total)

      

See: Custom Numeric Format Strings

+8


a source


Use "#, ## 0".



See: Quick Reference for .NET Format Strings

+2


a source


In addition to other great advice, you shouldn't use the string concatenation operator. Just do the following:

string text = string.Format("*Based on {0:#,##0} entries", total);

      

This makes it easier to read and requires less work.

+2


a source


Try this format.

{0:#,##0}

+1


a source


You can also do this:

string text = "*Based on " + total.ToString("#,##0") + " entries"; 

      

+1


a source


Here's an example using PowerShell. What matters is that the format string "{0:n0}"

.

3, 30, 300, 3000, 30000, 300000, 3000000, 30000000 |
    %{ "{0} -> {0:n0}" -f $_ }

      

What produces:

PS C: \ Users \ Damian> 3, 30, 300, 3000, 30000, 300000, 3000000, 30000000 | % {"{0} → {0: n0}" -f $ _}

3 -> 3
30 -> 30
300 -> 300
3000 -> 3,000
30000 -> 30,000
300000 -> 300,000
3000000 -> 3,000,000
30000000 -> 30,000,000

      

0


a source







All Articles