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 is supporting Monica
  • 142,542
  • 55
  • 282
  • 355
Kraz
  • 6,649
  • 5
  • 41
  • 67

4 Answers4

2

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

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

Live DEMO

toFixed on MDN

gdoron is supporting Monica
  • 142,542
  • 55
  • 282
  • 355
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
  • 72,560
  • 18
  • 107
  • 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
  • 7,777
  • 8
  • 30
  • 49