There are many ways to format number in Javascript. This following script formats a numeric value passed in to it with specified number of decimal values.
<script type=”text/javascript”>
Number.prototype.toDecimals=function(n){
n=(isNaN(n))?
2:
n;
var
nT=Math.pow(10,n);
function pad(s){
s=s||’.';
return (s.length>n)?
s:
pad(s+’0′);
}
return (isNaN(this))?
this:
(new String(
Math.round(this*nT)/nT
)).replace(/(\.\d*)?$/,pad);
}</script>
How to use this script:
var nMyNumber=123.3;
sMyFormattedNumber=nMyNumber.toDecimals(2);
this will return 123.30 for sMyFormattedNumber.
Be First To Comment
Related Post
Leave Your Comments Below