Go Back John Clare's Personal Website Sunday, May 20, 2012
How many decimal places?
In any webApp development, there are a number of wheels re-invented over and over. This is one of those wheels - a way to force client-side numeric format, specific to a particular decimal precision. Go ahead and play with the following form.
Number: Decimals:
The code hinges on one simple trick: integer rounding after multiplying the number by 10 to the [decimal] power, then dividing the number right back again - nice!  Anyway, here's the javascript:

...and here's a direct link to just download the script file: numberString.js


function formatNumberString(value, decimals)
{
   var str = (value == null) ? '0' : value.toString();
   str = str.replace(/^\s*|\s*$/g,"");
   str = (str.length == 0) ? '0' : str;

   var flt = (isNaN(str)) ? 0 : parseFloat(str);
   if (decimals == 0) return Math.round(flt).toString();

   var factor = Math.pow(10,decimals);
   flt = (Math.round(flt * factor)) / factor;

   var sides = flt.toString().split('.');
   var rside = (sides.length > 1) ? sides[1] : '0';

   for (var i=rside.length; i<decimals; i++) {rside += '0';}

   return sides[0] + '.' + rside.substr(0,decimals);
}