Interesting behaviour of type “decimal” in C#

前端 未结 5 1011
遇见更好的自我
遇见更好的自我 2021-02-12 13:34

If we declare padding as const decimal, the padding is not working.

mymoney = 1.2 and your money = 1.20, how can this behavior be explained?

class Progra         


        
5条回答
  •  孤独总比滥情好
    2021-02-12 14:09

    The compiler "knows" that adding zero to a value "shouldn't" change the value - so it optimizes this out. Now arguably that's an invalid optimization given the nature of decimal addition, but if you look at the generated code, you'll find the computation of mymoney doesn't involve an addition.

    I don't think I'd try to use adding 0.00m as a way to ensure a particular scale, to be honest. You could create your own code to enforce the scale, using decimal.GetBits and the constructor performing the reverse operation - but I don't think it would be terribly nice.

    Do you definitely need this "two decimal places" form as an intermediate value, or is it only for presentation? If it's the latter, I'd look at format strings instead.

提交回复
热议问题