Formatting numbers to a chosen number of decimal places : Number Format : Number Data Type JAVASCRIPT TUTORIALS


JAVASCRIPT TUTORIALS » Number Data Type » Number Format »

 

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 += ;
       count += 1;
     }
     while (pos < (count+numDecPlaces)){
       pos +=1;
     }
     return num.substring(0,pos);
}
// -->
</script>
</head>
<body onload="Calculate()">

</body>
</html>







HTML code for linking to this page:

Follow Navioo On Twitter

JAVASCRIPT TUTORIALS

 Navioo Number Data Type
» Number Format