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);
};
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.3it is around but not exactly33.3this 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
try
If you just want the string representation. You could try handing the floating point number as an integer. i.e.
33.3equals333then 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.