by Sai gowtham

How to format a number to specific decimal places in JavaScript

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

Consider we have a number like this.

const num  = 123.1390

Now we need to format the above number according to specific decimal places like 123.12 or 123.139.

Using toFixed() method

The toFixed() method formats a number and returns the string representation of a number. Be default the toFixed() method removes the fractional part.

It also accepts the optional argument called digits which means we need to specify the number of digits after the decimal point.

Let’s see an example:

const num  = 123.1390

            // fractional part is removed
console.log(num.toFixed()); // "123"

Have you seen our number is converted to string representation so that we need to convert the string back to a number by adding + operator.

console.log(+num.toFixed()); // 123

Formatting number to 2 decimal places

To format a number to 2 decimal places we need to pass 2 as an argument to the toFixed() method.

const num  = 123.1390

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

Similarly, we can format a number according to our needs like this.

const num  = 123.1390

          // 1 decimal place
console.log(+num.toFixed(1)); // 123.1

          // 2 decimal places
console.log(+num.toFixed(2)); // 123.13


          // 3 decimal places
console.log(+num.toFixed(3)); // 123.139

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 2022 (Beginner + Advanced)
JavaScript - The Complete Guide 2022 (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