c++doubleunordered-mapatof

Is `std::atof` guaranteed to produce identical output when given identical string input?


I'm reading double values from file as strings and parsing them with std::atof. Afterwards, I'm using the values as keys in a unordered map. It's seems to be working correctly, but is it guaranteed to work in 100% of the cases?

I'm asking the question because it's extremely hard to produce identical double value if you do any arithmetic operations with it.

Is std::atof guaranteed to produce exactly the same double value if given the same string value multiple times?


Solution

  • You can round trip a number with DBL_DIG significant digits or fewer via a std::string. Typically DBL_DIG is 15 but that depends on the floating point scheme used on your platform.

    That's not quite the same as what you are asking. For example, it's possible on some platforms to change the floating point rounding mode at runtime, so you could end up with different results even during the execution of a program. Then you have signed zeros, subnormal numbers, and NaN (in its various guises) to worry about.

    There are just too many pitfalls. I would not be comfortable using floating point types as map keys. It would be far, far better to use the std::string as the key in your map.