Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

converting decimal to int in c#

Tags:

c#

why percentage returns 0 when rate = 0.085 for example ?

int percentage = (int)rate*100;
like image 850
user310291 Avatar asked Sep 15 '10 18:09

user310291


3 Answers

The cast operation is applied before the multiplication. Try:

int percentage = (int)(rate*100);

Edit: Here's the C# guide on order of operator evaluation.

like image 66
womp Avatar answered Oct 26 '22 15:10

womp


It returns 0 because of order of operations. rate is cast as an integer prior to multiplying.

You need an extra set of parentheses to make this work.

int percentage = (int)(rate*100);

like image 43
Austin Salonen Avatar answered Oct 26 '22 14:10

Austin Salonen


Try:

int percentage = (int)(rate * 100);
like image 21
Spencer Ruport Avatar answered Oct 26 '22 14:10

Spencer Ruport