Author -  Sai gowtham

JavaScript - How to Round a number to 2 decimal places

In this tutorial, we are going to learn about How to round a number to 2 decimal places in JavaScript using toFixed() method.

Consider we have a number like this.

const num  = 1.1290

Now, we need to format the above number to 2 decimal places like this 1.12.

Using toFixed() method

To round a number to 2 decimal places in JavaScript, we can use the toFixed() method by passing 2 as a argument to it.

The toFixed() method takes the number of digits as argument and formats the number into the mentioned decimal places. By default the toFixed() method removes the fractional part.

Let’s see an example:

const num  = 1.1290

            // 2 decimal places
console.log(num.toFixed(2)); // " 1.12"

Note: The toFixed() returns string representation of number.

We need to convert the string back to a number by adding + operator.

console.log(+num.toFixed(2)); // 1.12

In the above example, we have a number but in case if you have string representation of number first convert it to number using the Number() method then call a toFixed() method on it.

const code  = '2.19055';
const result = Number(code).toFixed(2);


console.log(result); // 2.19

References

Css Tutorials & Demos

How rotate an image continuously in CSS

In this demo, we are going to learn about how to rotate an image continuously using the css animations.

How to create a Instagram login Page

In this demo, i will show you how to create a instagram login page using html and css.

How to create a pulse animation in CSS

In this demo, i will show you how to create a pulse animation using css.

Creating a snowfall animation using css and JavaScript

In this demo, i will show you how to create a snow fall animation using css and JavaScript.

Top Udemy Courses

JavaScript - The Complete Guide 2023 (Beginner + Advanced)
JavaScript - The Complete Guide 2023 (Beginner + Advanced)
116,648 students enrolled
52 hours of video content
$14.99 FROM UDEMY
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
631,582 students enrolled
49 hours of video content
$24.99 FROM UDEMY
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
203,937 students enrolled
31.5 hours of video content
$14.99 FROM UDEMY