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?

Jeromy French
  • 11,812
  • 19
  • 76
  • 129
bittersweetryan
  • 3,383
  • 5
  • 28
  • 42
  • 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? – Brian Roach Sep 14 '11 at 20:39
  • 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. – bittersweetryan Sep 14 '11 at 20:43
  • 2
    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. http://help.adobe.com/en_US/ColdFusion/9.0/Developing/WSc3ff6d0ea77859461172e0811cbec09af4-7fc3.html – Leigh Sep 15 '11 at 06:29
  • 7
    I am not sure I want to live a world where 0.06 + 0.01 does NOT equal 0.07. – Scott Stroz Sep 15 '11 at 14:15

1 Answers1

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));

?

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Thats it, dumping the value of the string shows .69999999999999; – bittersweetryan Sep 14 '11 at 20:51
  • 3
    `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. – Antony Sep 15 '11 at 06:13
  • @Antony - Yep. I have learned not trust it implicitly. As it is designed to favor readabilty over precision in many cases ;) – Leigh Sep 15 '11 at 06:22