【问题标题】:need to ignore decimal places from string if decimal places is .00如果小数位为 .00,则需要忽略字符串中的小数位
【发布时间】:2018-09-18 11:20:41
【问题描述】:

大家好,我想忽略这个来自字符串编号的.00。以下是我的示例输入和需要输出。我已经尝试过这段代码。 String.Format ("{0: n}", Amount) 但这段代码有问题。

如果值为10000. 00
我的代码会将其转换为"10, 000.00"
但我只需要"10, 000"

请帮我解决问题。

更多示例:

10000.00  -> "10,000"
10000.12  -> "10,000.12"
10000.1   -> "10,000.10"

【问题讨论】:

  • 10000.1小数点后一个位应该输出什么?
  • @DmitryBychenko 我需要这个 10000.1 所以它将是 10000.10
  • 我明白了;看来您必须在格式之间切换,这是实际问题

标签: c# number-formatting


【解决方案1】:

使用这种格式String.Format ("{0:0.##}", Amount)

或使用千位分隔符:"{0:#,0.##}" by @Dmitry Bychenko

【讨论】:

  • 千(组)分隔符:"{0:#,0.##}"
  • 我也需要这个 10000.1 所以它将是 10000.10
【解决方案2】:

所以你有某种 money:当且仅当我们有它们时,我们才会输出 cents

  10000.00  -> 10,000    (no cents; exactly 10000)
  10000.003 -> 10,000    (no cents; still exactly 10000) 
  10000.1   -> 10,000.10 (ten cents)
  10000.12  -> 10,000.12 (twelve cents)
  10000.123 -> 10,000.12 (still twelve cents)

我们可以格式化为"#,0.00" 的最后三种情况,而使用"#,0" 格式字符串的前两种情况是正确的。唯一的问题是区分这些情况。

我们可以尝试为此使用Math.Round()

  string result = d.ToString(Math.Round(d) != Math.Round(d, 2) ? "#,0.00" : "#,0");

演示:

decimal[] tests = new decimal[] {
  10000.00m,
  10000.003m,
  10000.10m,
  10000.12m,
  10000.123m,
};

string report = string.Join(Environment.NewLine, tests
  .Select(d => 
     $"{d,-10} -> {d.ToString(Math.Round(d) != Math.Round(d, 2) ? "#,0.00" : "#,0")}"));

Console.Write(report);

结果:

10000.00   -> 10,000
10000.003  -> 10,000
10000.10   -> 10,000.10
10000.12   -> 10,000.12
10000.123  -> 10,000.12

【讨论】:

    【解决方案3】:

    转换为整数将删除小数位,N2 格式将用作千位分隔符。

    ([int]10000.00).ToString("N");
    

    【讨论】:

      【解决方案4】:

      你可以添加另一个扩展

              var Amount = "1000.00";
              var r = String.Format("{0: n}", Amount).Replace(".00", "");
      

      【讨论】:

        猜你喜欢
        • 2021-02-04
        • 1970-01-01
        • 1970-01-01
        • 2015-12-03
        • 1970-01-01
        • 2021-01-02
        • 1970-01-01
        • 2015-08-25
        • 1970-01-01
        相关资源
        最近更新 更多