Javascript issue with rounding number

I knew that javascript might have the problem of rounding off with divisions, but not with multiplication. How do you solve them?

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 = 100andt = 57674

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

How could i get aff = 0.17?

+3
source share
4 answers
var aff = (r * 100).toFixed(2) + "%";

Live demo

toFixedon MDN

+1
source

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

+2
source

, aff , toFixed , "" + :

var n = 0.16999999999999998;

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

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

+1
source

This is a bug in JavaScript (although it also affects several other languages, such as Python), because it does not store an integer, which is a bit error (binary!). The only way around this is to round up to two decimal places.

0
source

All Articles