Why does 0.06 + 0.01 = 0.07 in ColdFusion?
Asked Answered
A

1

28

Why don't math operations in ColdFusion seem to be affected by floating point math issues? Take the code:

result = 0.06 + 0.01;

writedump(result);
writedump(result.getClass().getName());

Which outputs

0.07

java.lang.Double

However the equivlant Java code produces what I"d expect when adding two doubles:

public static void main(String[] args) {
    double a = 0.01d;
    double b = 0.06d;

    System.out.println(a + b); //0.06999999999999999
}

This is what I'd expect to see from ColdFusion because of the realities of floating math (http://download.oracle.com/docs/cd/E19957-01/806-3568/ncg_goldberg.html).

Does ColdFusion do some "magic" behind the scenes or am I looking at an isolated anomaly here?

Alarice answered 14/9, 2011 at 20:21 Comment(4)
Everything I google says there's nothing special about CF and it produces the results you expect (and people ask why, because they don't understand floating point precision). Are you sure nothing else is going on in your CF code?Lots
Yeah, that snippet is it. I just created the simplest of scenarios to see what would happen. Whats wierd is if I take that code a step further and do a = 0.01; b = 0.06; writedump(a.getClass().getName(); I get a String. There is definitely some implied conversion going on behind the scenes.Alarice
CF stores most values as strings initially. Only converting them to other types (number, date, etcetera) as needed. Such as when a mathematical operator like + is applied. help.adobe.com/en_US/ColdFusion/9.0/Developing/…Perr
I am not sure I want to live a world where 0.06 + 0.01 does NOT equal 0.07.Thermoscope
C
38

I strongly suspect it's simply rounding differently on output. In other words, the issue is still there - it just happens not to show up when this particular value is printed out with writedump.

What happens if you use:

writedump(String.valueOf(result));

?

Chemical answered 14/9, 2011 at 20:32 Comment(3)
Thats it, dumping the value of the string shows .69999999999999;Alarice
writedump and cfdump do lots of formatting - this makes quickly viewing complex objects very easy but it looks like it also introduces some ambiguity in cases like this.Doglike
@Doglike - Yep. I have learned not trust it implicitly. As it is designed to favor readabilty over precision in many cases ;)Perr

© 2022 - 2024 — McMap. All rights reserved.