How To Format Numbers in JavaScript

JavaScript doesn’t have many built-in methods to format numbers. Most of the time customized code needs to be used.¬†JavaScript Formatting numbers for decimals and significant digits is used to format the specific number of digits to be displayed. The significant digits are used to display the total number of digits that is present in decimal number i.e. before or after the decimal point.

There are two methods used for formatting numbers for decimals and significant digits

  1. number.toFixed( ): It is used to fix the number of digits to be used after the decimal point at right side.
  2. number.toPrecision( ): It is used to specify the total number of digits to be displayed, including both left and right side of the decimal point. It is also called as significant digits.

Syntax for toFixed( )

number.toFixed(n)

Syntax for toPrecision( )

number.toPrecision(n)

Example for JavaScript Formatting Number Methods

<!DOCTYPE html>
<head>
<title>Formatting numbers for decimals and significant digits</title>
</head>
<body>

<script type="text/javascript">

var n= 5.7832
document.write ("<b>Variable n :</b>  "+n+"<br>");
document.write("<b>n.toFixed() :</b>  " +n.toFixed()+"<br>");

document.write("<b>n.toFixed(3) :</b>  " +n.toFixed(3)+"<br></br>");

document.write("<b>n.toPrecision() :</b>  " +n.toPrecision()+"<br>");

document.write("<b>n.toPrecision(6) :</b>  " +n.toPrecision(6));

</script>

</body>
</html>
  • In the above program we have used both method toFixed( ) and toPrecision( ) which is used to format the decimal and significant digits.
  • we have used n.toFixed( ) method to round up the decimal value which is given in the above program.
  • n.fixed(3) is used to display total three digits after the decimal point.
  • n.toPrecision( 6) is used to show the total number of digits, including both left and right side of the decimal number.

JavaScript Formatting Number Demo

  • Save the file as number_methods.html in your system.
  • Just open the file in the browser, you will see the below picture in the browser.

When the execution process is completed successfully we will get the following output:

JavaScript Formatting Number Demo

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Speak Your Mind

*