May 10, 2022
How to Trim Number to 2 Decimal Places in Javascript
In this tutorial, you will learn how to trim number to 2 decimal places in javascript. 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 trim a number to 2 decimal places.
There are numerous ways to trim a number to 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
andh1
) using thedocument.querySelector()
method and stored them inbtn
andresult
variables. - We have created a global variable
num
and assigned982.5253
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 be982.53
which will be displayed on the screen insideh1
element.
let btnGet = document.querySelector('button'); let result = document.querySelector('h1'); let num = 982.5253; btnGet.addEventListener('click', () => { result.innerText = num.toFixed(2); });
HTML & CSS
div
,button
, andh1
). Thediv
element is just a wrapper for the rest of the elements.innerText
for thebutton
element is“Get”
.style.css
stylesheet inside thehead
element.script.js
with ascript
tag at the bottom.Javascript