Timo
Timo

Reputation: 8700

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()?

Upvotes: 0

Views: 287

Answers (1)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186833

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

Upvotes: 2

Related Questions