2
#include <iostream>

int main() 
{ 
    int val = std::stof("4.99") * 100; 

    std::cout << val; 

    return 0; 
}

I've tried other strings and they all seem to be converting correctly, but I am not sure what is happening behind the scenes that is causing this to output 498 instead of 499. In my use case, every string has a maximum of 2 decimal places.

Aaron
  • 483
  • 1
  • 6
  • 17

2 Answers2

5

The nearest IEEE754 float to 4.99 is 4.9899997711181640625. std::stof will return the latter.

That multiplied by 100 is 498.999969482421875 which is truncated to 498.

This is one of the pitfalls of floating point arithmetic I'm afraid; you need to take a lot of care when using a discontinuous function like a conversion of float to int; using std::lround on the result would work in your particular case.

Further reading: Is floating point math broken?

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
2

Use a proper function that will round your floating point number properly:

#include <cmath>
#include <iostream>
int main() 
{ 
    auto val = std::lround(std::stof("4.99") * 100);

    std::cout << val; 

    return 0; 
}
Matthieu Brucher
  • 21,634
  • 7
  • 38
  • 62