-2

I am getting a float input from the user with this code.

1. float change = Getfloat();
2. change *= 100;
3. int remainder = change;

However, when the user inputs 4.2 line 2 turns change variable to 419.999969 and line ends up with 419. How do I change the program so it effectively change the float to int.

  • hmmm one more floating point math issue.... – Sourav Ghosh Jul 07 '15 at 20:00
  • call `round` after `*100`. – Jason Hu Jul 07 '15 at 20:02
  • 1
    possible duplicate of [Why Are Floating Point Numbers Inaccurate?](http://stackoverflow.com/questions/21895756/why-are-floating-point-numbers-inaccurate) – too honest for this site Jul 07 '15 at 20:05
  • @SouravGhosh I tried to ask the same question right now and SO didn't show me anything that could catch an eye if I was FP-newbie. Not that OP did excessive research too, but maybe SO should show something more informative than just recent results for topics *like that*. – user3125367 Jul 07 '15 at 23:22
  • @user3125367: Don't worry about it. You're allowed to ask beginner questions, that is (in my opinion) one of the things the site is for. – Steve Summit Jul 08 '15 at 00:09

1 Answers1

-1

One way is to round to the nearest whatever. The simple version would be

change = (int)(change + 0.5);

(This would go between steps 2 and 3.) It rounds anything less than 0.5 down, and anything greater or equal to 0.5 up.

There may be additional complications if you want to round negative numbers, or if you want to round to something other than the nearest 1, but this should get you started.

Steve Summit
  • 45,437
  • 7
  • 70
  • 103