I have to add trailing zeros to a decimal value. Not only for displaying (so Format
is not an option), but in the actual underlying data, because the decimal precision is important in our application.
I tried:
decimal value = 1M
decimal withPrecision = value + 0.000M;
Which works well in many cases ... strangely not in all. I debugged into a case where the value in withPrecision was still 1M, by not seeing any difference in the value at runtime and the same hardcoded value in the immediate window. I also used decimal.GetBits to find differences - there are none.
I tried (as proposed here Adjusting decimal precision, .net):
decimal value = 1M
decimal withPrecision = value * 1.000M;
which works well - except for the case value is zero. Then the result is 0M without any trailing zeros. I also do not trust the solution, it may also not work in other cases.
Currently I'm with:
decimal value = 1M
decimal withPrecision = (value * 1.000M) + 0.000M;
Which works in all cases I currently found ... but doesn't look very trustworthy neither. I could also implement an exceptional case for zeros.
I think Format
and Parse
would work. I don't like it much. It doesn't look very fast and I don't understand why I have to put the decimal into a string just to manipulate it.
I start to believe that there is no clean solution for such a simple task.