3

I knew javascript could have rounding issue with divisions, but not with multiplication. How do you solve those?

var p = $('input[name="productsUS"]').val().replace(",", ".");
var t = $('input[name="productsWorld"]').val().replace(",", ".");

if (p >= 0 && t >= 1) {
    var r = p / t;
    r = Math.round(r * 10000) / 10000;
    var aff = (r * 100) + "%";

if p = 100 and t = 57674

r = 0.0017 (ok) and aff = 0.16999999999999998% (arg)

How could I obtain aff = 0.17?

gdoron
  • 147,333
  • 58
  • 291
  • 367
Kraz
  • 6,910
  • 6
  • 42
  • 70

4 Answers4

2

("0.16999999999999998").tofixed(2) gives you 0.17.

Aidanc
  • 6,921
  • 1
  • 26
  • 30
1
var aff = (r * 100).toFixed(2) + "%";

Live DEMO

toFixed on MDN

gdoron
  • 147,333
  • 58
  • 291
  • 367
1

If you want to aff to remain a Number instead of being converted to a String, you can use toFixed to work around the precision issues and then "cast" it back to a number using the unary + operator like so:

var n = 0.16999999999999998;

n = +n.toFixed(10); // 0.17

You probably want to use a higher precision than 2 decimal places to avoid rounding issues, I used 10 here.

Dagg Nabbit
  • 75,346
  • 19
  • 113
  • 141
0

That's a bug in JavaScript (although it also affects a few other languages, such as Python), due to the way it stores non-whole numbers being a bit buggy (binary!). The only way to work around it is to round it to two decimal places.

callumacrae
  • 8,185
  • 8
  • 32
  • 49