How to Round a Number to 1 Decimal Place in Javascript
In this tutorial, you will learn how to round a number to 1 decimal place in javascript. It is very likely that we will have a number of digits after the decimal point when we do a specific computation and obtain a decimal number. As a result, rounding a number to a specified number of decimal places for readability is very standard. For a newbie developer, it can be a bit tricky to round a number to 1 decimal place.
There are numerous ways to round a number to 1 decimal place. 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 round a number to 1 decimal place 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
that holds a decimal number as a value. - We have added a
click
event listener to thebutton
element. - We are executing the
toFixed()
method and passing 1 as a parameter. As a result, it will round the number to 1 decimal place. - We will display the result in the
h1
element.
let btnGet = document.querySelector('button'); let result = document.querySelector('h1'); let num = 230.5253; btnGet.addEventListener('click', () => { result.innerText = num.toFixed(1); });
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