Mega Code Archive

 
Categories / JavaScript Tutorial / Number Data Type
 

Formatting numbers to a chosen number of decimal places

< html> <head> <title>Formatting numbers to a chosen number of decimal places</title> <script type="text/javascript" language="javascript"> <!-- // function Calculate(){     var entry;     var first;     var second;     var numPlaces;     first = Number(1);     second = Number(3);     numPlaces = Number(2);     var n = first / second;     document.write(n+"  vs  "+formatNumber(n,numPlaces)); } function formatNumber(theNum, numDecPlaces) {      var num = new String();      num = "" + theNum;      var pos = 0;      count = 0;      while (num.substring(pos-1,pos)!== ".") {        pos += 1 ;        count += 1;      }      while (pos < (count+numDecPlaces)){        pos +=1;      }      return num.substring(0,pos); } // --> </script> </head> <body onload="Calculate()"> </body> </html>