Math.round( x ) in ECMAScript 262

Round a number to the closest integer.

Arguments

nametypedescription
x Number The value to operate upon.
Return Type
Number

Description

This method always rounds the number to the nearest integer. To round a number to a specified number of decimal places (for formatting, such as displaying currency), use the Number.toFixed() method. Alternatively, you may use a hack like:

var x = 16.457221;
x = Math.round( x * 100 ) / 100;
// ** x is close to 16.46

...but as noted above, the value may not always be exactly what you want. The above, for example, might display as 16.45999999999 due to the limitation of representing floating point numbers as a fixed number of binary digits. When dealing with fixed precision amounts like currency, its best to track all values as integers (e.g. the number cents, rather than dollars) and convert to decimal using toFixed() for display purposes only.

(An actual example of the problem is that 0.06 + 0.01 will produce the value 0.069999999999999 rather than 0.07.)