Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Float Value Is Lost in Int [duplicate]

Trying to cast float to int but there's something missing

float submittedAmount = 0.51f;

int amount = (int)(submittedAmount * 100);

here is watch. look at the variable values

Why is the answer 50?

like image 748
levi Avatar asked Feb 11 '13 09:02

levi


2 Answers

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

like image 160
Øyvind Bråthen Avatar answered Sep 20 '22 05:09

Øyvind Bråthen


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

like image 26
Soner Gönül Avatar answered Sep 22 '22 05:09

Soner Gönül