Posted By

inkdeep on 04/21/08


Tagged

utility numberformat


Versions (?)

Who likes this?

4 people have marked this snippet as a favorite

rafael
apawson
nkm
mundgold


Javascript number formatting (number_format ported from PHP)


 / Published in: JavaScript
 

URL: http://kevin.vanzonneveld.net

The numberformat function from PHP rewritten as javascript. From the super badass http://kevin.vanzonneveld.net/techblog/article/phpjslicensing/

  1. function number_format( number, decimals, dec_point, thousands_sep ) {
  2. // http://kevin.vanzonneveld.net
  3. // + original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
  4. // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  5. // + bugfix by: Michael White (http://crestidg.com)
  6. // + bugfix by: Benjamin Lupton
  7. // + bugfix by: Allan Jensen (http://www.winternet.no)
  8. // + revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
  9. // * example 1: number_format(1234.5678, 2, '.', '');
  10. // * returns 1: 1234.57
  11.  
  12. var n = number, c = isNaN(decimals = Math.abs(decimals)) ? 2 : decimals;
  13. var d = dec_point == undefined ? "," : dec_point;
  14. var t = thousands_sep == undefined ? "." : thousands_sep, s = n < 0 ? "-" : "";
  15. var i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;
  16.  
  17. return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
  18. }

Report this snippet  

You need to login to post a comment.