Format number for only 2 digits

4

I have a script that returns: 4.499999999999999

But I wanted it to return only 4.4 or round to 4.5, so I do not want it to be more than 1 digit after the comma, how to do it?

    
asked by anonymous 19.03.2015 / 22:41

2 answers

6

To round to the nearest number, the simplest is to use toFixed :

var x = 4.499999999999999;
var y = x.toFixed(1);

document.querySelector("body").innerHTML += "<p>" + y + "</p>";

Now to round down, you need to use the floor function and some more calculation:

var x = 4.499999999999999;
var y = Math.floor(10*x)/10;

document.querySelector("body").innerHTML += "<p>" + y + "</p>";

Note that the first method converts the number to a string, while the second method only performs a calculation with it (the result remains a number). I can not think of an example, but it's possible that even after the calculation the number is not as accurate as you intended (given the limitations of floating-point representation) - so it's advisable to use toFixed too in the result if you use method 2.

    
19.03.2015 / 22:46
4

If the number is in string format and you want to round to string you have two possibilities:

19.03.2015 / 22:53