0

I have a QVariant that stores a double value. One place the value is coming from is a QDoubleSpinBox (but not only!), which has a min (0.3) and max (1.0) as limits.

I've noticed that I get an exception (the code is written like this) when I set the value below the minimum. What's surprising is that I'm actually setting the value to 0.3.

Through debugging I found out that the following code is the reason why this is happening:

// value is QVariant
auto valueDouble = value.toDouble();
// use valueDouble

What happens is that when I set the value to 0.3 internally

  • value = 0.3
  • valueDouble = 2.9999999999999999

And 2.9999... is definitely below 0.3 hence the reason why I get the exception. Of course the 0.3 is probably a display "error" by the debugger inside Qt Creator. Nevertheless I'm more concerned about the internal error.

I also tried using QVariant::toFloat() and I got 0.300000012.

Needless to say this not only creates poor user experience but internally also leads to all sorts of issues.

I can make it so that the QDoubleSpinBox doesn't allow such behaviour however as I've mentioned such values comes from different locations in the applications so this issue needs to be handled on a deeper level.

rbaleksandar
  • 8,713
  • 7
  • 76
  • 161
  • I assume you mean `valueDouble = 2.9999999999999999e-1` – Alan Birtles Mar 02 '20 at 07:46
  • @AlanBirtles Could be. Unable to see it in the debugger. As for the "question has already been answered" I don't agree. My issue comes from string to double conversion (spin box is just a part of it). Also extracting the initial value from a `QVariant` should not lead to different results. – rbaleksandar Mar 02 '20 at 07:48
  • 1
    If you read the duplicate you'll see that your essential problem is that `0.3` is not representable as a floating point number so it has to be stored as `0.29999` or `0.3000012`, you can probably fix your problem by explicitly setting your minimum value to `0.299999` – Alan Birtles Mar 02 '20 at 07:50
  • @AlanBirtles The minimum/maximum are just for the spinbox situation. Also the limits are automatically set (by values extracted from XML data). – rbaleksandar Mar 02 '20 at 07:55
  • You could just subtract a small value (any value less than half the number of decimal places displayed/allowed by the spinbox, e.g. 0.003 for 2dp) from the minimum and add to the maximum before setting them on the spinbox – Alan Birtles Mar 02 '20 at 13:03
  • @AlanBirtles But I cannot know what the value is (since it comes mostly from XML data). Plus it adds an arithmetic step that poses exactly the issue that you've mentioned (with the duplicate link) - rounding errors. – rbaleksandar Mar 02 '20 at 14:57

0 Answers0