June 29, 2020
How to Round Off Numbers to 2 Decimal Places in Javascript
- We have selected 2 elements (
button
andh1
) using thedocument.querySelector()
method and stored them inbtn
andresult
variables. - We have created a global variable
num
and assigned123.788975488
as a value. - We have added a
click
event listener to thebutton
element. - We are executing the
toFixed()
method and passing 2 as a parameter. The output will be123.79
which will be displayed on the screen insideh1
element.
let btnGet = document.querySelector('button'); let result = document.querySelector('h1'); let num = 123.788975488; btnGet.addEventListener('click', () => { result.innerText = num.toFixed(2); });
In the following example, we will simply round off
123.788975488
to 2 decimal places and display it on the screen. We are going to use thetoFixed()
method to achieve it easily. To access thetoFixed()
method, a variable should be of number type.toFixed()
method simply takes one optional parameter where you can specify the number of digits to appear after the decimal. In case, you do not pass any parameter, it will be treated as 0. Please have a look over the code example and steps given below.HTML & CSS
div
,button
, andh1
). Thediv
element is just a wrapper for the rest of the elements.style.css
stylesheet inside thehead
element.script.js
with ascript
tag at the bottom.Javascript