0

When I multiply 100*4.6 or 100*4.9, the code produces 459.99999999999994 and 490.00000000000006, respectively. It only does this for these specific numbers. When I multiply 100*4.7, for example, it correctly produces the number 470.

I tried parseFloat() on a whim and it did not help (nor did I expect it to). I do not want to use Math.round or .toFixed() because, in my full code, I randomly generate the number that gets multiplied by 100, so sometimes it should have a decimal. (For example, if the code generates 100 * 3.652, the answer should be 365.2, so I do not want to simply round as a band-aid solution.)

Why is this multiplication error happening for these specific numbers?

Javascript:

var Product = 100* 4.6;
$(".Product").html(Product);

var Product2 = 100* 4.7;
$(".Product2").html(Product2);

var Product3 = 100* 4.9;
$(".Product3").html(Product3);

HTML:

<span class="Product"></span>
<br>
<span class="Product2"></span>
<br>
<span class="Product3"></span>

JSFiddle:

http://jsfiddle.net/2owtz3vq/1/

Snoops
  • 215
  • 1
  • 12
  • 1
    Welcome to floating-point arithmetic. – Robert Harvey Dec 28 '18 at 16:56
  • 1
    Because floats cannot represent all values with 100% accuracy – Caius Jard Dec 28 '18 at 16:57
  • 1
    ^^ ...as implemented by IEEE-754 binary floating point numbers. – T.J. Crowder Dec 28 '18 at 16:57
  • Mmm, okay thank you. I was not aware of this. I glanced through that other question and I'll reading it more thoroughly, but, before this question gets closed out as a duplicate, is there a quick fix for this? Something akin to wrapping with `parseFloat()` perhaps? – Snoops Dec 28 '18 at 17:00
  • How much precision do you actually need? If you round to six decimal places (or even twelve), you'll never encounter this problem again, unless, of course, you try to compare two unrounded floating point numbers without an epsilon. – Robert Harvey Dec 28 '18 at 17:06
  • 1
    `var Product = Number(100*4.6).toFixed(2); $(".Product").html(Product); var Product2 = Number(100* 4.7).toFixed(2); $(".Product2").html(Product2); var Product3 = Number(100* 4.9).toFixed(2); $(".Product3").html(Product3);` try this one – Sushil Dec 28 '18 at 17:08
  • Based on the other post, it seems like `var Product2 = 10*100* 4.6; $(".Product2").html(Product2/10);` will also work (and it seems to work in the JSFiddle). Am I correct that this is another potential solution? – Snoops Dec 28 '18 at 17:15

0 Answers0