Reputation: 149
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
Upvotes: 4
Views: 494
Reputation: 187040
The second one should be
var cost1 = (int)(amount * 1000);
You have to multiply with 1000 and then convert the result. In your example you are converting first and then multiplying.
See Operator precedence and associativity
Upvotes: 3
Reputation: 1062780
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:
Upvotes: 15