I understand that there are rounding errors but can anyone explain why I get such different results using these different methods:
decimal amount = 9.990M;
var cost = Convert.ToInt32(amount*1000);
var cost1 = (int) amount*1000;
I get:
cost = 9990
cost1 = 9000
Try (int)(amount*1000)
. In the Convert
, the brackets enforce the precedence, but cast (int)
takes precedence over the multiply - so you current have: ((int)amount)*1000
, which rounds (during the cast) to 9.
In particular, see "7.2.1 Operator precedence and associativity" in the MS spec, which defines cast ahead of multiplication:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With