JavaScript Snippet – A Much Required Float Formatter

Just like PHP’s SPRINTF.

function float_format(n, digits){
  var matches;

  digits = "number" === typeof digits ? Math.max(digits, 0) : 2;  /* normalize range: 0-inf+ */
  n = String(Number(n));                                          /* normalize number */

  matches = n.match(/(^\d+)\.{0,1}(\d*$)/);
  
  return 0 === digits ? matches[1] /* just whole */
                      : matches[1] + "." + (matches[2] + new Array(digits).join("0")).substring(0, digits)
                      ;
}

/*===--- examples ---===*/

float_format(10.20004146687235, 25);   /* 10.2000414668723500000000000 */
float_format(10.20004146687235, 2);    /* 10.20                        */
float_format(10.20004146687235);       /* 10.20                        */
float_format(10.20004146687235, 0);    /* 10                           */

Leave a Reply