Skip to content

JavaScript toFixed() Function | format a number

  • by

The JavaScript toFixed() function is used to format a number using fixed-point notation. This method rounds the string to a specified number of decimals and also converts a number to a string.

number.toFixed(x)

x: Default is 0 used, Number of digits after the decimal place to display in the result.

Example toFixed() Function in JavaScript

Simple HTML example code converts a number to a string with 2 decimal points using the toFixed() Function.

If the number of decimals is higher than in the number, zeros are added.

<!DOCTYPE html>
<html>

<body>

  <script>
    var n = 111.6394;
    var res = n.toFixed(2)

    console.log(res); 
    console.log(typeof(res)); 

  </script>

</body>
</html>

Output:

JavaScript toFixed() Function

More example

var totn_number = 123.456789;

console.log(totn_number.toFixed());
console.log(totn_number.toFixed(1));
console.log(totn_number.toFixed(2));

Format number to always show 2 decimal places

(Math.round(num * 100) / 100).toFixed(2);

Code

var num1 = "1";
var res1 = (Math.round(num1 * 100) / 100).toFixed(2);

var num2 = "1.341";
var res2 = (Math.round(num2 * 100) / 100).toFixed(2);

var num3 = "1.345";
var res3 = (Math.round(num3 * 100) / 100).toFixed(2);

Do comment if you have any doubts or suggestions on this JS function topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading