Format number for only 2 digits

Asked

Viewed 4,323 times

6

I have a script that returns: 4.499999999999

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

2 answers

7


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>";

Already to round down, it is necessary to use the function floor and some other 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 only performs a calculation with it (the result remains a number). I can’t think of an example, but it is possible that even after the calculation the number is not as accurate as you want (given the limitations of the floating point representation) - so it is advisable to use toFixed also in the result, if you use method 2.

5

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

1 - keep string and simply cut the size after stitch (floor)

var n = '4.499999999999999'.split('.') ;
n = [n[0], n[1][0]].join('.');                          // '4.4'

2 - round to 4.5 in the case of your example

var n = parseFloat('4.499999999999999', 10).toFixed(1); // '4.5'

If the number is in format number and you want to round off to number you have three possibilities:

1 - round (round to nearest house)

var n = Math.round(4.499999999999999 * 100) / 100;      // 4.5

2 - Ceil (round to the top)

Math.ceil(4.499999999999999 * 10) / 10;                 // 4.5

3 - floor (round down)

var n = Math.floor(4.499999999999999 * 10) / 10;        // 4.4
  • 1

    +1 and it is still possible to use both the strategies, if applicable (e.g., convert from string to number, round using the choice method, and convert from number to string again).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.