How to prevent ToString("0,0") to return 00

.net, asp.net-mvc-3, c#

Solution

I suspect you want:

myVariable.ToString("#,0", ...)

Although I'd be surprised if one of the standard string formats didn't handle this. For example, you could use:

myVariable.ToString("N0", ...)

Also note that instead of using the invariant culture and then replacing comma with space, you could create your own culture (based on the invariant culture, potentially) with a `NumberGroupSeparator` of " ".

Sample code:

// You don't need to create this every time. Create it once and put it in a static variable.
var culture = (CultureInfo) CultureInfo.InvariantCulture.Clone();
culture.NumberFormat.NumberGroupSeparator = " ";

Console.WriteLine(12345.ToString("N0", culture)); // 12 345

Problem

I have a bunch of integers that I have to display in one of my views. I display them this way: ``` int myVariable = 12500; myVariable.ToString("0,0", System.Globalization.CultureInfo.InvariantCulture).Replace(",", " ") ``` If myVariable contains 12500, it will display: 12 500. This is exactly what I want. However, if myVariable contains 0, it will display: 00. Instead of 00, I want 0 to be displayed. I've looked on MSDN about Custom number formats and I haven't found anything that could help me. If it's possible, I would like to not be able to do some more string management (replace, etc). Just switching the format from 0,0 to something that would work for me.

Original source