0

I know there are different solutions using round() or floor() or something else, but why is my programm below behaving like this?

float number;
int result;

number = 60.44;
result = ( number - (int) number ) * 100;

In this case result displays as 43 instead of 44, why?

hansvurst
  • 1
  • 2
  • 2
    Because the value is not exactly 60.44; it is 60.439998626708984375. See [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – molbdnilo Nov 09 '21 at 13:43
  • 1
    To be precise, `60.44` is exactly `60.44` with 32-bit floats. The issue here is that `60.44 - 60.0` is `0.439999...` rather than the expected `0.44`. Using a `double` rather than a `float` would fix the issue in this particular case, but similar issues will pop up with other numbers even when using `double` – Omer Tuchfeld Nov 09 '21 at 13:46
  • I use integer pennies in transaction balancing. If you don't want to deal with floating point rounding errors, then don't! – Kenny Ostrom Nov 09 '21 at 14:21

0 Answers0