How to Round Off Numbers to 2 Decimal Places in Javascript

In this tutorial, you will learn how to round off numbers to 2 decimal places in javascript. It is pretty much common to round off a number to certain decimal places for the sake of readability.  For instance, if you want to display a currency, then you will round it off to 2 decimal places.
  • 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 and assigned 123.788975488 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. The output will be 123.79 which will be displayed on the screen inside h1 element.
let btnGet = document.querySelector('button');
let result = document.querySelector('h1');

let num = 123.788975488;

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