Use a custom thousand separator in C#

后端 未结 4 1828
走了就别回头了
走了就别回头了 2020-11-27 05:37

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 s

相关标签:
4条回答
  • 2020-11-27 06:17

    Easiest way...

    num.ToString("### ### ### ### ##0.00")
    
    0 讨论(0)
  • 2020-11-27 06:30

    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.

    0 讨论(0)
  • 2020-11-27 06:32

    I suggest you find a NumberFormatInfo which most closely matches what you want (i.e. 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
        }
    }
    
    0 讨论(0)
  • 2020-11-27 06:37

    Create your own NumberFormatInfo (derivative) with a different thousand separator.

    0 讨论(0)
提交回复
热议问题