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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/752145/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 23:48:03  来源:igfitidea点击:

Use a custom thousand separator in C#

c#formattingtext-formatting

提问by Luk

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 显示为 1 000 000 而不是 1,000,000

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

(不,String.Replace()这不是我想使用的解决方案:P)

采纳答案by Jon Skeet

I suggest you find a NumberFormatInfowhich most closely matches what you want (i.e. it's right apart from the thousands separator), call Clone()on it and then set the NumberGroupSeparatorproperty. (If you're going to format the numbers using currency formats, you need to change CurrencyGroupSeparatorinstead/as well.) Use that as the format info for your calls to string.Formatetc, and you should be fine. For example:

我建议你找到一个NumberFormatInfo最接近你想要的东西(即它与千位分隔符分开),调用Clone()它然后设置NumberGroupSeparator属性。(如果您要使用货币格式对数字进行格式化,则您也需要更改CurrencyGroupSeparator/更改。)将其用作呼叫string.Format等的格式信息,您应该没问题。例如:

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
    }
}

回答by Lucero

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

使用不同的千位分隔符创建您自己的NumberFormatInfo(衍生)。

回答by Gordon Bell

Easiest way...

最简单的方法...

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

回答by Invvard

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() 方法中。