# Compare doubles: 50000.3 > 50000.3 = true!?

I encounter some strange behaviour of a greater than comparison:

``````var teststring as string = "50000.3"
var testdouble as double = teststring.toDouble
var testcalc as double = 50000.1+0.2
var test as Boolean = testdouble > testcalc
System.DebugLog "test = "+test.ToString  // outputs true!?
``````

why might that be?

Do you need to check if one is bigger or is it enough to know if they are equal / unequal?

https://docs.xojo.com/Equals

1 Like

I would like to hear from Xojo, that the calculated 50000.3 is not smaller than the â€śstring-originatedâ€ť 50000.3
50000.3 > 50000.3 should be false, hence:
testdouble > testcalc should be false
But Xojo gives out a â€śtrueâ€ť!

check the debugger youâ€™ll see a double is not to be expected as-is.

50000.3 could as well be stored as 50000.2999999999999999999999999999999999 in your computer.
Itâ€™s not a xojo thing, itâ€™s how doubles work.

``````System.DebugLog "testdouble = "+testdouble.toString+", testcalc = "+testcalc.ToString
``````

gives out:
testdouble = 50000.300000, testcalc = 50000.300000

Youâ€™re not seeing the actual 15-digit fractional portion. ToString is rounding it. You cannot reliably compare double values. Thatâ€™s what Equals is for: Equal to a given number of decimals. Or round both values yourself and compare. As @DerkJ said, itâ€™s just the nature of double precision in computer programming. Thereâ€™s a reason theyâ€™re not used for monetary applications.

FWIW,
50000.3 is stored as 50000.300000000003
50000.1 is 50000.099999999999
50000.1 + 0.2 is 50000.299999999999

So, yes, testdouble is greater than testcalc.

50000.300000000003 > 50000.299999999999

1 Like

Crazy. Thank you for the detailed explanation.

No. Try to express 0.1 in binary and youâ€™ll understand â€¦

Not crazy. Itâ€™s how floating point works.

1 Like

If the CPU could split the number (the integer and decimal parts) and use both as integers, this problem wouldnâ€™t exist. But probably this would be incompatible with how they could or couldnâ€™t workâ€¦

1 Like

Most pocket calculators work that way. But the deduction is incorrect. Try division or taking roots or sinus or numbers like pi etc and you are back to square one - you do Maths with limited precision.

Awesome, I didnâ€™t know about Double.Equals, and I happen to have a need right now, thanks! This forum rocks

5 Likes
Forum for Xojo Programming Language and IDE. Copyright Â© 2021 Xojo, Inc.