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
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