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?

3
  • stackoverflow.com/questions/1458633/… Commented Apr 25, 2012 at 14:27
  • are you still having problems? Commented Apr 25, 2012 at 15:10
  • Nop, toFixed() was the solution. I just gave time to people to put up answers and to pick one. Commented Apr 25, 2012 at 16:40

4 Answers 4

2

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

Sign up to request clarification or add additional context in comments.

Comments

1
var aff = (r * 100).toFixed(2) + "%";

Live DEMO

toFixed on MDN

Comments

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.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.