JavaScript Number Type
Round
We can round numbers up and down as we want by using the Math.round,
Math.ceil and Math.floor static methods or by using the
toPrecision method.
- Math.round: Rounds to the closest integer.
- Math.ceil: Rounds up to the closest integer.
- Math.floor: Rounds down to the closest integer.
- toPrecision: Returns a string with the number in the specified precision.
Code example: Math.round
const a = 12.567const b = 13.456console.log(Math.round(a)) // 13console.log(Math.round(b)) // 13
We can see that a is rounded up because the fractional portion
of the number is greater than 0.5.
Code example: Math.ceil
const a = 12.567const b = 13.456console.log(Math.ceil(a)) // 13console.log(Math.ceil(b)) // 14
ceil always rounds up, so both numbers end up rounded up to the
nearest integer.
Code example: Math.floor
const a = 12.567const b = 13.456console.log(Math.floor(a)) // 12console.log(Math.floor(b)) // 13
floor always rounds down, so both numbers end up rounded down to the
nearest integer.
Code example: toPrecision
const a = 12.567const b = 13.456console.log(a.toPrecision(2)) // "13"console.log(b.toPrecision(2)) // "13"console.log(a.toPrecision(3)) // "12.6"console.log(b.toPrecision(3)) // "13.5"
toPrecision with precision set to two significant digits is almost
identical to round except that we get a string value back instead.
When we set the precision to three significant digits, our numbers are rounded up to nearest tenth.