2

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

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

Currently, in an attempt to do this, I'm using the following formatting code:

  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 necessary. How do I properly format my numbers?

Thank you

1
  • No it doesn't! What makes you think that? Commented Apr 19, 2010 at 21:25

6 Answers 6

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

See: Standard Numeric Format Strings

- or -

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

See: Custom Numeric Format Strings

Sign up to request clarification or add additional context in comments.

2 Comments

The first will add a single decimal place, the second will not.
Notice the 0 in N0 -- this specifies the number of decimal places.
2

Use "#,##0".

See: Quick Reference for .NET Format Strings

Comments

2

In addition to the other great advice, You shouldn't be using the string concatenation operator. Simply do this:

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

This makes it easier to read, and requires less work.

Comments

1

Try this format.

{0:#,##0}

Comments

1

You can also do this:

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

Comments

0

Here's a sample using PowerShell. The important point is that the format string is "{0:n0}".

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

Which 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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.