How would I separate thousands with space in C#

怎甘沉沦 提交于 2019-11-28 07:13:42
Tim S.

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"

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.

try this

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

You will received : 134 566 548,00

Don't forget your culture.

with a custom format string, but use '#' not '0's a 0 is a mandatory token it will be there no matter how long the number is, the pound sign (#) is optional token, it will only be used for digits actually in the number.

  Decimal.ToString("# ###.00")  

NOTE. I'll leave this here, but @Tim S' answer is a better one.

When I try this I see it only generates the first separator... I guess the separator only works for commas and periods here. As a workaround (up to the maximum size number you expect), try this instead.

  Decimal.ToString("# ### ### ### ###.00")  

Norwegian locale uses spaces as a separator, so if you were designing a website or application specifically for Norwegians, then you could use:

(123897.11).ToString("n",new CultureInfo("nb-NO"))

Which results in

"123 897,11"

Obviously, if you're not writing an application for the Norwegian market, then this would be a silly solution.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!