简体   繁体   English

C#小数记住精度:如何调整

[英]C# decimal remembers precision: how to adjust

Decimal remembers its number of decimal places: 小数会记住其小数位数:

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

I am in a situation where I do not control the serialization (so I cannot use a more explicitly formatted stringify), but there is a requirement to output exactly 2 decimal places. 我处于无法控制序列化的情况(因此,我无法使用更明确地格式化的stringify),但是需要精确输出2个小数位。

So, I am trying to force any decimal into the same value but with 2 decimal places . 因此,我试图将任何十进制强制为相同的值, 但要保留两位小数

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

It is achievable with ToString("F") and then Decimal.Parse() . 这可以通过ToString("F")然后通过Decimal.Parse() But is there a neater way than via ToString() ? 但是,有没有一种比通过ToString()更整洁的方式?

In order to ensure/increase "precision" up to 2 digits after the decimal point you can add 0.00m : 为了保证/增加“精确”高达2小数点你可以添加后的数字0.00m

1.1m + 0.00m == 1.10m

The same idea generalized: 相同的想法可以概括为:

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);

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

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