Trying to cast float to int but there's something missing
float submittedAmount = 0.51f;
int amount = (int)(submittedAmount * 100);
Why is the answer 50?
Trying to cast float to int but there's something missing
float submittedAmount = 0.51f;
int amount = (int)(submittedAmount * 100);
Why is the answer 50?
Because of floating point aritmethics, the multiplied value isn't exactly 51. When I tried now, *0.51f * 100* gave the result 50.9999990463257.
And when you parse 50.9999990463257 to and int, you surely get 50.
If you want calculations like this to be exact, you will have to use a type like decimal
instead of float
.
If you want to understand why, read the article I have linked below.
What Every Computer Scientist Should Know About Floating-Point Arithmetic
Try with
int amount = (int)(submittedAmount * 100.0);
When you write 0.51f
is not exactly 0.51
Read this great article called What Every Computer Scientist Should Know About Floating-Point Arithmetic
Use Convert class. Otherwise the answer still will be 50.
var amount = Convert.ToInt32(submittedAmount * 100.0));
0.51f
is actually 0.509999999999
. because floating points are imprecise.
I would like to add that, do not use float
for monetary calculations. Use decimal
instead.