JavaScript provides three methods to round a number to the nearest integer, round up or round down. All these are static methods of the Math
object that you can access directly to round numbers.
Math.round()
— Rounds a number to the nearest integer. If the fraction value is 0.5 or higher, round up.Math.ceil()
— Rounds up to the nearest integer.Math.floor()
— Rounds down to the nearest integer.
Math.round(5.287) // 5
Math.round(5.87) // 6
// Rounds up
Math.ceil(5.33) // 6
// Rounds down
Math.floor(5.87) // 5
To round a number to 2 decimal places, you need to do a bit of calculation, as shown below:
const num = Math.round(5.87456 * 100) / 100
console.log(num) // 5.87
Alternatively, you can use the toFixed()
method to round a number to 2 decimal places in JavaScript. The toFixed()
method rounds and formats the number to 2 decimal places:
const num = 5.87456
const str = num.toFixed(2)
console.log(str) // 5.87
The toFixed()
method takes the number of digits after the decimal point as input and returns a string representation of the number.
To convert the string back to a floating point number, you can use the parseFloat()
method or the Number()
constructor:
const num = 5.87456
const str = num.toFixed(2)
console.log(str) // 5.87
console.log(typeof str) // string
const final = parseFloat(str)
console.log(final) // 5.87
console.log(typeof final) // number
const final2 = Number(str)
console.log(final2) // 5.87
console.log(typeof final2) // number
✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.