How to Get Only 2 Decimal Places in Javascript

In this tutorial, you will learn how to get only 2 decimal places in javascript. When we get a decimal number after performing a particular computation, it is highly likely that we will end up with a bunch of digits after a decimal point. Thus, it is pretty much common to trim a number to 2 decimal places for the sake of readability.  For a newbie developer, it can be a bit tricky to get a decimal number up to only 2 decimal places.

There are numerous ways to get a decimal number up to only 2 decimal places. We are going to use the simplest approach which involves the usage of the toFixed() method. It converts the number to string and rounds it to a specified number of decimals.

In the following example, we have one global variable that holds a number. Upon click of a button, we will trim the number to 2 decimal places and display the result on the screen. Please have a look over the code example and the steps given below.

  • We have selected 2 elements (button and h1) using the document.querySelector() method and stored them in btn and result variables.
  • We have created a global variable num that holds a decimal number as a value.
  • We have added a click event listener to the button element.
  • We are executing the toFixed() method and passing 2 as a parameter. As a result, it will trim the decimal number up to 2 decimal places.
  • We will display the result in the h1 element.
let btnGet = document.querySelector('button');
let result = document.querySelector('h1');

let num = 5142.550053;

btnGet.addEventListener('click', () => {
    result.innerText = num.toFixed(2);
});