How to Allow Only 4 Digits After Decimal in Javascript

In this tutorial, you will learn how to allow only 4 digits after decimal in javascript. When we perform a particular calculation and generate a decimal number, there is a good probability that many digits will come after the decimal point. To make numbers easier to understand, they are rounded to a certain number of decimal places. For a newbie developer, it can be a bit tricky to allow only 4 digits after decimal.

There are numerous ways to allow only 4 digits after decimal. 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 allow only 4 digits after decimal in the number 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 4 as a parameter. As a result, it will round the number to 4 decimal places.
  • We will display the result in the h1 element.
let btnGet = document.querySelector('button');
let result = document.querySelector('h1');

let num = 1425.566546557470;

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