简体   繁体   English

在C#中使用自定义的千位分隔符

[英]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 例如:将1000000显示为1000000,而不是1000000

(no, String.Replace() is not the solution I'd like to use :P) (不, String.Replace()不是我要使用的解决方案: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. 我建议您找到一个与您想要的内容最匹配的NumberFormatInfo (即,它与千位分隔符分开),在其上调用Clone() ,然后设置NumberGroupSeparator属性。 (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. (如果要使用货币格式来格式化数字,则也需要更改/更改CurrencyGroupSeparator 。)将其用作调用string.Format等的格式信息,就可以了。 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 : 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. 并且可以跳过“ nfi”初始化并将其作为参数直接放入ToString()方法中。

最简单的方法

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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