0

Possible Duplicate:
Is JavaScript's Math broken?

I'm attempting to add up three input fields, each containing a value of 33.3 which should total 99.9, however they are totaling to 99.89999999999999

Could someone explain how this is happening. Below is my code. Thanks in advance.

$("#modify-funding input.percentCalc").sumValues()

$.fn.sumValues = function () {
    var sum = 0;
    this.each(function () {
        sum += $(this).fieldVal();
    });
    return sum;
};

$.fn.fieldVal = function () {
    var val;
    if ($(this).is(':input')) {
        val = $(this).val();
        alert("val " + val);
    } else {
        val = $(this).text();
    }       
    return parseFloat(('0' + val).replace(/[^0-9-\.]/g, ''), 10);
};
Community
  • 1
  • 1
Code Junkie
  • 7,602
  • 26
  • 79
  • 141
  • 1
    Floating point numbers are approximations, minor errors are part and parcel. – Vala Jul 16 '12 at 14:35
  • 2
    This somehow reminds me of Jon Skeet's [OMG Ponies!!! (Aka Humanity: Epic Fail)](https://msmvps.com/blogs/jon_skeet/archive/2009/11/02/omg-ponies-aka-humanity-epic-fail.aspx). You know how [IEEE 754 floating point](http://en.wikipedia.org/wiki/Floating_point#IEEE_754:_floating_point_in_modern_computers) work right? Yeah, the precision is that of the closest binary value in binary16. – Fabrício Matté Jul 16 '12 at 14:43

1 Answers1

1

Welcome to the wonderful world of floating point numbers. Floating points are aproximations of the number you want to represent. Thus when you save a number as 33.3 it is around but not exactly 33.3 this error adds up after multiple operations. The best way to compare floats is to not test for equality but to test weather they are in a range.

Instead of

if(x == 99.9)

try

if(Math.abs(99.9 - x) < .1)

If you just want the string representation. You could try handing the floating point number as an integer. i.e. 33.3 equals 333 then when you are turning it back into a string you add the decimal back in where appropriate. This would be the best solution for your problem.

secretformula
  • 6,414
  • 3
  • 33
  • 56