【问题标题】:Custom number group (thousand separator) for 1000,000 format in c#c#中1000,000格式的自定义数字组(千位分隔符)
【发布时间】:2018-11-08 05:17:03
【问题描述】:

我的代码如下我正在尝试对数字进行自定义分组 例如:1000000 应该是 1000,000

我尝试了许多搜索结果,允许千位分隔符和自定义分组,但每个结果都给出了 10,00,000 之类的结果

decimal value = decimal.Parse(txtamount.Text.Trim());
txtamount.Text = value.ToString("#,###0");

在这段代码中,我也尝试过下面的代码

txtamount.Text = String.Format("{0:n0}", value);
txtamount.Text = value.ToString("#,##0", new System.Globalization.CultureInfo("en-US"));
txtamount.Text = value.ToString("0,0.0",CultureInfo.InvariantCulture); //-->1,000,000.0

这不是数字的正常千位分隔符分组。 我正在尝试以 1000,000 的格式输出

【问题讨论】:

标签: c#


【解决方案1】:

只有一个分组分隔符,你可以使用这个:

// create a writable copy of the culture of your choice
var ci = (CultureInfo)CultureInfo.GetCultureInfo("en-us").Clone();

// change the group sizes: the first one after 3 digits (counting backwards)
// NO second (third, ..) one!
ci.NumberFormat.NumberGroupSizes = new[]{3,0};

// and use it 
// the , in the format means "use a group separator", it does NOT specify a position
var millionString1 = 1_000_000.ToString("#,#", ci); // 1000,000
var millionString2 = 1_000_000.ToString("N0", ci); // also 1000,000

但请注意,1000 万现在将变为 10000,000。

docs

【讨论】:

    【解决方案2】:

    由于它是自定义格式,因此您需要转义逗号 ,

    string.Format("{0:####\\,###}",value)
    

    【讨论】:

    • 对于小于 1000 的数字似乎会导致 ,10
    【解决方案3】:

    没有custom formatter 似乎是不可能的,但可以在后面插入逗号。例如:

    string value = "1234567.890"
    string result = Regex.Replace(value, @"(\d+)(\d\d\d)", "$1,$2");  // result = "1234,567.890"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-19
      • 1970-01-01
      • 2018-11-17
      • 1970-01-01
      • 2021-12-16
      相关资源
      最近更新 更多