Last Updated On By Anmol Lohana
JavaScript toFixed() method is a built-in method of JavaScript programming language just like many others. It is used to format a number in a specific number of digits to the decimal’s right and require the formatted number in string form. It will format a number using fixed-point notation.
Syntax
number.toFixed(value);
This method takes a single parameter value that is required, and there is no optional parameter. It will take the decimal values and signify the number of digits occurring after the decimal point.
Passing a parameter inside the method is optional, so if you do not give any parameter to the method, this method returns the value only, emitting the entire decimal part.
It will return the number in string representation. And the output will have the exact digits after the decimal place as mentioned in the toFixed() method.
Let’s have a look at examples.
Table of Contents
<!DOCTYPE html>
<html lang="en">
<head>
<title>toFixed() Method</title>
</head>
<body>
<p id="demo"></p>
<p id="demo1"></p>
<script>
var num=213.73145;
var f_num = num.toFixed();
document.getElementById("demo").innerHTML = "Original Number : " + num;
document.getElementById("demo1").innerHTML = "After Method calling : " + f_num;
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<title>toFixed() Method</title>
</head>
<body>
<p id="demo"></p>
<p id="demo1"></p>
<script>
var num=213.73145;
var f_num = num.toFixed(3);
document.getElementById("demo").innerHTML = "Original Number : " + num;
document.getElementById("demo1").innerHTML = "After Method calling : " + f_num;
</script>
</body>
</html>
The toFixed() method can convert exponential numbers into numbered string representation with a specific number of digits after the decimal point.
Let’s have a look at its example too.
<!DOCTYPE html>
<html lang="en">
<head>
<title>toFixed() Method</title>
</head>
<body>
<p id="demo"></p>
<p id="demo1"></p>
<script>
var num=213.73145e+5;
var f_num = num.toFixed(3);
document.getElementById("demo").innerHTML = "Original Number : " + num;
document.getElementById("demo1").innerHTML = "After Method calling : " + f_num;
</script>
</body>
</html>
Here, in the above-given example, we can notice that the toFixed() method is formatting a number of exponential notation values. Still, it is also expanding the number according to the value we passed inside the method by adding zeroes in it.
In this article, we discussed the JavaScript toFixed() method; we used it to format a number in a specific number decimal digits and return the result in a string form. We performed various examples to see the functions of the toFixed() method.