简体   繁体   中英

Use a custom thousand separator in C#

I'm trying not to use the ',' char as a thousand separator when displaying a string, but to use a space instead. I guess I need to define a custom culture, but I don't seem to get it right. Any pointers?

eg: display 1000000 as 1 000 000 instead of 1,000,000

(no, String.Replace() is not the solution I'd like to use :P)

I suggest you find a NumberFormatInfo which most closely matches what you want (ie it's right apart from the thousands separator), call Clone() on it and then set the NumberGroupSeparator property. (If you're going to format the numbers using currency formats, you need to change CurrencyGroupSeparator instead/as well.) Use that as the format info for your calls to string.Format etc, and you should be fine. For example:

using System;
using System.Globalization;

class Test
{
    static void Main()
    {
        NumberFormatInfo nfi = (NumberFormatInfo)
            CultureInfo.InvariantCulture.NumberFormat.Clone();
        nfi.NumberGroupSeparator = " ";

        Console.WriteLine(12345.ToString("n", nfi)); // 12 345.00
    }
}

创建具有不同的千位分隔符的自己的NumberFormatInfo (派生)。

There's a slightly simpler version of Jon Skeet one :

using System;
using System.Globalization;

class Test
{
    static void Main()
    {
        NumberFormatInfo nfi = new NumberFormatInfo {NumberGroupSeparator = " ", NumberDecimalDigits = 0};

        Console.WriteLine(12345678.ToString("n", nfi)); // 12 345 678
    }
}

And the 'nfi' initialization could be skipped and put directly as parameter into the ToString() method.

最简单的方法

num.ToString("### ### ### ### ##0.00")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM