0

I need to get the exact input value of double spin box. I set 8 decimal digit for my Spinbox. When I type 0,6000000 what I get in the debug is 0,59999999999998 as in the picture (sometimes it is 0,6000000000002).

pic1

I tried to convert this value to 0,60000000 using QString::number and convert it again to double. What I receive is the old value again (0,59999999999998).

enter image description here But when I print these values out, it prints 0,60000000.

Because I have my calculation after that, so I need the exact input value, otherwise my calculation will be wrong. In this case I should become exact 0,60000000). How can I do that?

songvan
  • 369
  • 5
  • 21
  • 1
    Possible duplicate of [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – TrebledJ Apr 09 '19 at 09:37
  • @TrebledJ: thanks, the problem may be the same, but i still do not have solution for this case :) – songvan Apr 09 '19 at 09:41
  • 1
    I'm presuming you'll be using the input double in some arithmetic and calculations? Perhaps you may want to look at [C++ calculating more precise than double or long double](https://stackoverflow.com/questions/14637621/c-calculating-more-precise-than-double-or-long-double). Otherwise, it's probably best to use strings and line-edits instead (but that doesn't seem to be what you're trying to achieve). – TrebledJ Apr 09 '19 at 09:45
  • 1
    Ah ok, reread your question about needing the exact value. For precision, you might want to load another library (e.g. the GNU Multiprecision Library, recommended in [Decimal type in Qt (C++)](https://stackoverflow.com/questions/2547686/decimal-type-in-qt-c) as well). I think Boost also has a multiprecision library for math? – TrebledJ Apr 09 '19 at 10:01
  • 1
    @TrebledJ: thanks for your help. I tried with my own solution `QString valueAsText = locale().toString( p_value, 'f', decimals() );` I got `valueAsText` exactly as I typed. From that i can get integer part and decimal part (using string) and then convert again into `int`. and it works :) – songvan Apr 09 '19 at 12:14
  • 1
    The root of the problem is that you are trying to to represent a decimal floating point on a computer that thinks in binary floating point. 0.6 can not be perfectly represented in floating point binary. The closest you can get would be 0.1001(repeated). It's slightly smaller, but gets closer the farther out. Refer to [decimal to binary converter](http://decimal-to-binary.com/decimal-to-binary-converter-online.html?id=475) and [Why is 1.1 + 2.2 != 3.3?](http://www.cplusplus.com/forum/beginner/180393/). – jwernerny Apr 09 '19 at 17:57

0 Answers0