1

I am getting wrong conversion value from QString to double. Below is my code.

QString value = "0.525";
bool status = false;
double doubleVal = value.toDouble(&status);

The value I get for doubleVal is 0.52500000000000002. and I was expecting it be 0.525.

Can someone help me regarding this? Thanks.

  • 5
    Base-10 decimals and base-2 floating point values cannot accurately represent the same (distinct) set of values. The floating point literal `0.525` translates to a floating point value that can only be accurately represented when using an infinite number of bits. See [IEEE 754 Converter](http://www.h-schmidt.net/FloatConverter/IEEE754.html) and observe the repeating digits in the mantissa. – IInspectable Jul 29 '16 at 12:22
  • 2
    Possible duplicate of [Error reading float values](http://stackoverflow.com/questions/6577561/error-reading-float-values) – IInspectable Jul 29 '16 at 12:29
  • 1
    Possible duplicate of [Why Are Floating Point Numbers Inaccurate?](http://stackoverflow.com/questions/21895756/why-are-floating-point-numbers-inaccurate) – underscore_d Jul 29 '16 at 15:39
  • That's not a "wrong value". That's just a less-accurate-than-you-like approximation of the value. Floating-point numbers are not guaranteed to be exact, at least not for all values. But you can make it perfectly accurate in this case by comparing/printing in a way that accounts for the minor inaccuracy. – underscore_d Jul 29 '16 at 15:41

2 Answers2

4

Your expectation is rather unfounded if unfortunately all too common. You can only be sure that all non-integer real numbers have an infinite-length representation in a positional system in any base (see this answer).

A finite-length representation of a rational number exists only in certain bases. It happens that the rational number 525/1000 does not have finite-length representation in base 2; the representation in that base is 0.100001(1001). It has a finite-length representation in base 10 (among others).

The double{0.525} has only an infinite length representation in base 10. The number 0.52500000000000002 is truncated to the number of decimal positions that cover the number of mantissa bits in IEEE-754 double precision binary representation.

Since a float or double is a positional representation in a base-2 system, you should expect that any non-integer real will need an infinite-length representation to be accurately represented, and only some will be able to be represented in a finite length.

Community
  • 1
  • 1
Kuba hasn't forgotten Monica
  • 95,931
  • 16
  • 151
  • 313
2

It's a known issue. Or, rather, not an issue at all, which is why it's been closed without fixing.

This shouldn't be a problem: you should not rely on on a double having a specific value in all of its digits. Allow for a reasonable epsilon deviation / accuracy.

Violet Giraffe
  • 32,368
  • 48
  • 194
  • 335