Round a number to 2 decimal places in JavaScript

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.

  1. Math.round() — Rounds a number to the nearest integer. If the fraction value is 0.5 or higher, round up.
  2. Math.ceil() — Rounds up to the nearest integer.
  3. 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.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.