1

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.

anastaciu
  • 23,467
  • 7
  • 28
  • 53
Deek880
  • 29
  • 3
  • Why do you think it is the input that is truncating? Have you considered the possibility that the input is accurate but the output is only 6 digits? – 1201ProgramAlarm Feb 13 '21 at 17:26
  • It's the opposite, `std::cout` doesn't print all of the digits. Try for example `std::cout << std::fixed << std::setprecision(2) << num;`. Or your `atof`-implementation is utterly broken. – Lukas-T Feb 13 '21 at 17:26
  • Use of double for the receiving value instead of float plus std::fixed of ios_base::std for fstream is returning an accurate result – Deek880 Feb 15 '21 at 14:58

1 Answers1

1

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.

anastaciu
  • 23,467
  • 7
  • 28
  • 53
  • 1
    Thanks everyone for the replies. Use of double instead of float and std::: fixed , ios_base::fixed has solved the problem – Deek880 Feb 15 '21 at 14:55
  • @Deek880, I'm glad you solved it, consider [accepting the answer](https://meta.stackexchange.com/a/5235/684852) if you feel it helped you. – anastaciu Feb 15 '21 at 15:52