Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

in C# (int) decimal and Convert.Int32(decimal) give me two different results

Tags:

c#

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
like image 752
NetRunner Avatar asked Nov 30 '22 11:11

NetRunner


1 Answers

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:

  • 7.5: Primary: x.y f(x) a[x] x++ x-- new typeof default checked unchecked delegate
  • 7.6: Unary: + - ! ~ ++x --x (T)x
  • 7.7: Multiplicative: * / %
  • etc
like image 67
Marc Gravell Avatar answered Dec 15 '22 11:12

Marc Gravell