Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would I separate thousands with space in C#

Assume I have the following decimal number that I have to format so that every thousand should be separated with a space:

 897.11 to 897.11
 1897.11 to 1 897.11
 12897.11 to 12 897.11
 123897.11 to 123 897.11

I have tried Decimal.ToString("0 000.00"). Although this works pretty well when the number is 1897.11. But when it's 897.11 I get 0 897.11.

like image 778
Mikayil Abdullayev Avatar asked Jul 08 '13 13:07

Mikayil Abdullayev


People also ask

What is the thousand separator format?

The character used as the thousands separatorIn the United States, this character is a comma (,). In Germany, it is a period (.). Thus one thousand and twenty-five is displayed as 1,025 in the United States and 1.025 in Germany. In Sweden, the thousands separator is a space.


3 Answers

Pass in a custom NumberFormatInfo with a custom NumberGroupSeparator property, and use the #,# format to tell it to do number groups. This example uses the invariant culture's number format as its basis.

var nfi = (NumberFormatInfo)CultureInfo.InvariantCulture.NumberFormat.Clone();
nfi.NumberGroupSeparator = " ";
string formatted = 1234897.11m.ToString("#,0.00", nfi); // "1 234 897.11"
like image 151
Tim S. Avatar answered Oct 17 '22 08:10

Tim S.


You need a custom number format provider where you change the character yourself:

    static void Main(string[] args)
    {
        decimal d = 2000000;

        var f = new NumberFormatInfo {NumberGroupSeparator = " "};

        var s = d.ToString("n", f); // 2 000 000.00
    }

Here I also specify to format it as a number (using "n"), please see this link for other formatting options:

Standard Numeric Format Strings

In this case, it won't work if you format as a currency or a percentage, because as you may already note the NumberFormatInfo has separate properties for those.

The current culture format info can be found on System.Globalization.CultureInfo.CurrentCulture.NumberFormat.

like image 23
Adam Houldsworth Avatar answered Oct 17 '22 08:10

Adam Houldsworth


try this

int testNumber = 134566548;
Console.WriteLine(string.Format("{0:N}", testNumber));

You will received : 134 566 548,00

Don't forget your culture.

like image 11
Matthieu M Avatar answered Oct 17 '22 10:10

Matthieu M