A decimal
value in C# has a fixed decimal point and therefore knows how many decimal places it had when it was created:
25.000m.ToString()
returns "25.000"
, unlike a double
which has a floating point.
This question is not about how to display a number with fixed decimals, I know the various string conversion options. This is about the internal representation of the decimal
data type, I'm just using .ToString()
to show it.
Now I want to round a number to a fixed number of decimals. This works:
Math.Round(25.0000m, 3) -> 25.000
But when the number of decimals was less than 3, or it comes from a double
, it doesn't (of course):
Math.Round(25.00m, 3) -> 25.00
Math.Round((decimal) 25.0000d, 3) -> 25
(decimal) Math.Round(25.0000d, 3) -> 25
So how can I round any double
number to a decimal
with 3 forced places?
Since it's hard to explain, suggestions for a better title are welcome!