-1

I am trying to convert a string to a double or float in C++, but the result is not exact. For example:

double d1 = stod("2.16"); //d1 ends up being 2.1600000000000001

float f1 = stof("2.16"); //f1 ends up being 2.16000009

Is it possible to convert "2.16" to the actual value 2.16 ( 2.16000000 float or 2.1600000000000000 double) using C++ libraries? I need the exact values for some calculations so I don't need it to be printed as 2.16, I need the exact number.

Alan Birtles
  • 32,622
  • 4
  • 31
  • 60
pc5000
  • 1
  • 1
  • 1
    `the actual value 2.16 (float or double)` Such value does not exists. If you need "exact" values, then use integers. – KamilCuk Jul 28 '20 at 15:12
  • 2
    _"Is it possible to convert "2.16" to the actual value 2.16 (float or double) using C++ libraries?"_ No, it's not possible. Numbers are stored as binary in memory and the binary representation of 2.16 has infinite digits. – Thomas Sablik Jul 28 '20 at 15:15
  • Floating point is now exact. See [What Every Computer Scientist Should Know About Floating-Point Arithmetic](https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html) and [Is floating point math broken?](https://stackoverflow.com/q/588004/5910058) – Jesper Juhl Jul 28 '20 at 15:19
  • @JesperJuhl -- that should be "floating point is **not** exact", shouldn't it? Or did it magically do the impossible? – Pete Becker Jul 28 '20 at 20:59
  • @PeteBecker Of course, I meant "*not* exact". – Jesper Juhl Jul 29 '20 at 05:15

1 Answers1

2

How to convert string to double or float without loosing precision in C++

By only converting values that can be represented precisely in the target type.

Is it possible to convert "2.16" to the actual value 2.16 (float or double)

No, because the actual value 2.16 doesn't exist in those types (assuming binary IEEE-754 representation). The best that can be achieved is to convert to a representable value that is closest to 2.16.

I need the exact values for some calculations

If this is true, then you need to not use floating point numbers. Floating point can only be used when errors in accuracy are acceptable.


can I at least get conversion which is not smaller than the original nubmer

You indeed can, if you set the rounding mode accordingly:

std::fesetround(FE_UPWARD);
eerorika
  • 232,697
  • 12
  • 197
  • 326
  • Thank you all for your explanations, but since it is not possible to get exact conversion, can I at least get conversion which is not smaller than the original nubmer: float f1 = stof("2.54"); //this gets me 2.5399996? – pc5000 Jul 28 '20 at 15:30
  • @pc5000 See edit. – eerorika Jul 28 '20 at 15:40
  • Here is your 2.54 example with rounding up: [https://ideone.com/QVy4V2](https://ideone.com/QVy4V2) – drescherjm Jul 28 '20 at 15:46