1

I have the following Jquery function on change event on a textbox

  $('input:text[id$=txtText1]').change(GetTotal);

This calls GetTotal function

 function GetTotal() {

            var value1 = txtText1.val();
            var value2 = txtText2.val();
                 var sum = add(value1, value2)

                 $('input:text[id$=txtSubTotals]').val(sum);
}

This is the add function

 function add() {
            var sum = 0;
            for (var i = 0, j = arguments.length; i < j; i++) {
                if (IsNumeric(arguments[i])) {
                    sum += parseFloat(arguments[i]);
                }
            }
            return sum;
        }

In textbox 1 the value is 1.45 and in Textbox 2 it is 1.44 instead of getting 2.89. I am getting the following value 2.8899999999999997

kalls
  • 2,797
  • 17
  • 55
  • 75
  • 2
    See http://stackoverflow.com/questions/588004/is-javascripts-floating-point-math-broken – j08691 Feb 13 '13 at 21:41
  • avoid floating point math - if you really need to, do "integer" math on the parts (i.e. the before decimal part and the after decimal part) then put them back together when done – kinakuta Feb 13 '13 at 21:42

2 Answers2

5

Welcome to the world of floating point math (there is a lot written about this on the internet, but this is how the type of floating point math in javascript and other languages works). You can read about floating point issues in many articles. Here's one. The issue is that some normal decimal values can't be represented precisely in the floating point format so you get tiny errors from what you would expect.

In general, if you aren't using a large number of decimal points in your original numbers, then rounding your value down to a smaller number of decimal points will eliminate the discrepancy.

For example, if you want to make sure you get 2.89, then you can round your value to a certain number of decimal points and you will get the desired answer.

You may want to change how you put it into the total field like this:

$('input:text[id$=txtSubTotals]').val(sum.toFixed(2));

Or, you could even use a value of something like 6 as in sum.toFixed(6) and it would still solve your issue.

If you really want perfect precision (like very important financial calculations), then there are libraries that don't use floating point for accurate financial math or you can actually convert to an integer number of cents and do all your math operations as cents and only put the decimal point back at the very end.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
1

You could use JavaScript toFixed() Method.

http://www.w3schools.com/jsref/jsref_tofixed.asp

Mr_Nizzle
  • 6,644
  • 12
  • 55
  • 85