【问题标题】:C# decimal remembers precision: how to adjustC#小数记住精度:如何调整
【发布时间】:2017-05-09 12:03:45
【问题描述】:

Decimal 记住它的小数位数:

Console.WriteLine(1.1m); // 1.1
Console.WriteLine(1.10m); // 1.10

我处于不控制序列化的情况(因此我不能使用更明确格式化的字符串化),但需要精确输出 2 位小数。

所以,我试图将任何小数强制为相同的值但有 2 个小数位

var d = Decimal.Round(1.1m, 2, MidpointRounding.AwayFromZero); // Try to increase precision
Console.WriteLine(d); // Is 1.1, but I need 1.10

通过ToString("F")Decimal.Parse() 可以实现。但是有没有比通过ToString() 更简洁的方式?

【问题讨论】:

  • 如果你想增加“精度”添加0.00m:1.1m + 0.00m == 1.10m
  • 你是如何序列化的?您可能可以控制序列化程序本身如何序列化小数。

标签: c# decimal precision digits


【解决方案1】:

为了确保/增加“精度”到小数点后2 位数,您可以添加0.00m

1.1m + 0.00m == 1.10m

同样的想法概括:

private static decimal FormatOut(decimal value, int afterDecimal) {
  // rounding up and adding 0.00…0 - afterDecimal zeroes        
  return Decimal.Round(value, afterDecimal, MidpointRounding.AwayFromZero) + 
         new decimal(0, 0, 0, false, (byte)afterDecimal);
}

...

decimal result = FormatOut(1.1m, 2);

// 1.10
Console.Write(result);

【讨论】:

    猜你喜欢
    • 2010-11-11
    • 2017-09-25
    • 1970-01-01
    • 1970-01-01
    • 2011-02-14
    • 2019-07-13
    • 2011-03-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多