Javascript Reference - JavaScript toFixed() Method








The toFixed() method converts a number into a string, keeping a specified number of decimals.

The toFixed() method returns a string representation of a number with a specified number of decimal points.


var num = 10; 
console.log(num.toFixed(2)); //"10.00" 

num = 10.005; 
console.log(num.toFixed(2)); //"10.01" 
        

The code above generates the following result.

Browser Support

toFixed Yes Yes Yes Yes Yes




Syntax

number.toFixed(x)

Parameter Values

Parameter Description
x Optional. The number of digits after the decimal point. Default is 0

Technical Details

A String type value representing a number with the exact number of decimals

Example

The following code shows how to convert a number into a string, keeping only two decimals.


<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">test</button>
<!--from   ww w.j  a v  a  2  s  .c om-->
<p id="demo"></p>

<script>
function myFunction() {
    var num = 5.56789;
    var n = num.toFixed(2)
    document.getElementById("demo").innerHTML = n;
}
</script>

</body>
</html>

The code above is rendered as follows:





Example 2

The following code shows how to convert a number without keeping any decimals.


<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">test</button>
<p id="demo"></p>
<script>
function myFunction() {<!--  w  w w . jav a 2 s.  co m-->
    var num = 5.56789;
    var n = num.toFixed()
    document.getElementById("demo").innerHTML = n;
}
</script>
</body>
</html>

The code above is rendered as follows:

Example 3

The following code shows how to convert a number which has fewer decimal places than requested.


<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">test</button>
<p id="demo"></p>
<script>
function myFunction() {<!--   ww w  .  ja va2 s  .  c om-->
    var num = 5.56789;
    var n = num.toFixed(10)
    document.getElementById("demo").innerHTML = n;
}
</script>
</body>
</html>

The code above is rendered as follows: