简体   繁体   中英

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.

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() . But is there a neater way than via ToString() ?

In order to ensure/increase "precision" up to 2 digits after the decimal point you can add 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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