-2

Why when I use multiplication

float a= 1.0500000f;
float b= a*100.0f;

why b is 104.99999 but not 105.0 ?

and when I

int f= (int)b;

f is 104

mrgloom
  • 20,061
  • 36
  • 171
  • 301
  • 3
    [Is floating point math broken?](http://stackoverflow.com/questions/588004/is-floating-point-math-broken) – 001 Apr 10 '14 at 13:32
  • 4
    See [here](http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html) for everything you need to know. As for the senond part, it's due to truncation. – Phylogenesis Apr 10 '14 at 13:32
  • there are lots of questions about this "problem" on this site. Read more http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html – phuclv Apr 10 '14 at 13:42

1 Answers1

1

Floating point numbers are not infinitely accurate -- the wikipedia page on Float numbers is quite interesting to read.

On your second question: (int)b truncates anything that occurs after the comma. This means that, in your case, 104.99999 becomes 104. So when you create a rounding error, and then cast it to an integer, you are indeed running the risk of getting a lower number.

Lee White
  • 3,649
  • 8
  • 37
  • 62