0

I have a string that I want to convert to a double using std::stod. However, the output of std::stod is not what I would expect. For example, if my string is 6.1, the output of std::stod is 6.0999999999999996.

Is there anything I can do to either make it so std::stod returns 6.1 or to convert the 6.099...6 to 6.1?

Aelion
  • 379
  • 1
  • 5
  • 16

1 Answers1

1

Nope. std::stod returns a double, and on most implementations, a double is a binary floating point type.

That will not have an exact representation of 6.1.

If you need 6.1 exactly, then consider using an integral type with an appropriate scaling factor, or use a decimal type from a 3rd party library.

See Is floating point math broken?

Bathsheba
  • 231,907
  • 34
  • 361
  • 483