0

Possible Duplicate:
Is JavaScript’s Floating-Point Math Broken?

For some reason when I'm multiplying numbers, when the number gets larger than 10,000,000 I start to see problems with accuracy. Here's the code:

this.multiply = function(quantity, value, id) {
    var math = quantity * value;
    document.getElementById(id).value = math.toFixed(2);
}

Here's the values that I get:

11111     -> 11111.00
111111    -> 111111.00
1111111   -> 1111111.04
11111111  -> 11111110.45
111111111 -> 111111116.41

It just gets worse from there. Any idea what could be causing this or how to fix this accuracy problem?

Community
  • 1
  • 1
Jason Mell
  • 103
  • 1
  • 9
  • 1
    What is the code that calls `multiply`? Where are the arguments coming from? – Niet the Dark Absol Dec 10 '12 at 17:41
  • 3
    Welcome to floating point arithmetic. – zzzzBov Dec 10 '12 at 17:41
  • Some bug in your code before doing toFixed. On chrome it is correct 111111111.00 for 111111111 – closure Dec 10 '12 at 17:43
  • zzzzBov was quite right. Don't you know that floating point arithmetic isn't 100% reliable. This isn't issue for js only it's a programming issue. – kidwon Dec 10 '12 at 17:44
  • See also: https://en.wikipedia.org/wiki/IEEE_floating_point#Formats: `Each finite number is described by three integers: s = a sign (zero or one), c = a significand (or 'coefficient'), q = an exponent. The numerical value of a finite number is (−1)s × c × b^q` – apsillers Dec 10 '12 at 17:45
  • @Kolink: It's just a dumbed down version of the real name, that's all. The arguments, when checked, are correct. – Jason Mell Dec 10 '12 at 17:46

0 Answers0