JavaScript Number toFixed() method

JavaScript: number toFixed() function; Through this tutorial, i am going to show you how to use the number method called toFixed with the help of examples.

JavaScript Number toFixed() method

The toFixed() method in JavaScript is used to format a number using fixed-point notation. It can be used to format a number with a specific number of digits to the right of the decimal. The toFixed() method is used with a number as shown in above syntax using the ‘. ‘ operator.

Syntax of JavaScript Number toFixed() method

number.toFixed(n);

Here,

  • The first thing is n is an optional parameter in toFixed function.
  • The second thing is, n is a number of digits after the decimal place to display in the result.

Example 1 – JavaScript Number toFixed() method

Using the javascript number toFixed() method, you can format numbers in one decimal point and more decimal points or without decimal; as follows:

 var number = 111.123456;

 number.toFixed();
 number.toFixed(1);
 number.toFixed(2);

 //Output
 111
 111.1
 111.12

Example 2 – Javascript toFixed With and Without Rounding

Using the toFixed() method, you can round a number with or without using .toFixed function; as follows:

<!DOCTYPE html>
<html>
   <head>
      <title>Javascript tofixed With and Wthout Rounding Example</title>
   </head>
<body>
<button onclick="calFucntion()">Click & See Result</button>
<br><br>
<b>With Round :-</b> <p id="withRound"></p>
<b>Without Round :-</b> <p id="roundValue"></p>
<script>
  function calFucntion() {
    var num = 5285.8556545;
    var withRound = num.toFixed(2);
    var with2Decimals = num.toString().match(/^-?\d+(?:\.\d{0,2})?/)[0];
    document.getElementById("withRound").innerHTML = withRound;
    document.getElementById("roundValue").innerHTML = with2Decimals;
}
</script>
</body>
</html>

Example 3 – javascript tofixed method

var num = 12345.6789;
num.toFixed();       // Returns '12346': note rounding, no fractional part
num.toFixed(1);      // Returns '12345.7': note rounding
num.toFixed(6);      // Returns '12345.678900': note added zeros
(1.23e+20).toFixed(2);  // Returns '123000000000000000000.00'
(1.23e-10).toFixed(2);  // Returns '0.00'
2.34.toFixed(1);        // Returns '2.3'
2.35.toFixed(1);        // Returns '2.4'. Note it rounds up
2.55.toFixed(1);        // Returns '2.5'. Note it rounds down - see warning above
-2.34.toFixed(1);       // Returns -2.3 (due to operator precedence, negative number literals don't return a string...)
(-2.34).toFixed(1);     // Returns '-2.3'

Conclusion

In this tutorial, you have learned how to use javascript .tofixed function with examples

If you have any questions or thoughts to share, use the comment form below to reach us.

More JavaScript Tutorials

Leave a Comment