Is there an alternative to atof in C++

561 views Asked by At

I am finding that atof is limited in the size of a string that it will parse.

Example:

float num = atof("49966.73");
cout << num;

shows 49966.7

num = atof("499966.73");
cout << num;

shows 499966

I need something that will parse the whole string accurately, to a floating point number, not just the first 6 characters.

1

There are 1 answers

2
anastaciu On

Use std::setprecision and std::fixed from <iomanip> standard library, as mentioned in the comments, still, there will be conversion issues due to lack of precision of float types, for better results use double and std::stod for conversion:

float num = std::atof("499966.73");
std::cout << std::fixed << std::setprecision(2) << num;
double num = std::stod("499966.73");
std::cout << std::fixed << std::setprecision(2) << num;

The first prints 499966.72, the latter 499966.73.