# Round a number to 2 decimal places in JavaScript

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Nov 26, 2022, updated Nov 27, 2022. Topics: JavaScript.
Canonical URL: https://attacomsian.com/blog/javascript-round-numbers

> Learn how to round numbers in JavaScript using ceil(), floor(), and round() methods.

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

```javascript
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:

```javascript
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:

```javascript
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:

```javascript
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
```
