Formatting numeric amounts in Javascript

16 January 2009   1 comment   Javascript

Powered by Fusion×

Dear Lazyweb,

Is there a better method than this to format numeric amounts? Here's a solution I picked up from somewhere and slightly modified. It's heavily string based but passed the tests:

function format_amount(i) {
  if(isNaN(i)) { i = 0.00; }
  var minus = '';
  if(i < 0) { minus = '-'; }
  i = Math.abs(i);
  i = parseInt((i + .005) * 100);
  i = i / 100;
  s = new String(i);
  if(s.indexOf('.') < 0) { s += '.00'; }
  if(s.indexOf('.') == (s.length - 2)) { s += '0'; }
  s = minus + s;
  return s;
}

The "tests" are:

format_amount(100)       == "100.00";
format_amount(100.0)     == "100.00";
format_amount(100.05)    == "100.05";
format_amount(100.051)   == "100.05";
format_amount(-100)      == "-100.00";
format_amount(-100.0)    == "-100.00";
format_amount(-123.45)   == "-123.45";
format_amount(-123.450)  == "-123.45";

So functionally it's OK but I'm not sure it's the best way to do it.

Comments

djo
Google for "javascript sprintf" throws a few things up. More code, but at least printf format strings are pretty universal.
Thank you for posting a comment

Your email will never ever be published


Related posts

Previous:
Earth, observed - The Big Picture - Boston.com 16 January 2009
Next:
Nasty surprise of Django and gettext 18 January 2009
Related:
Credit Card formatter in Javascript 19 November 2013
Comparing REAL values in PostgreSQL 07 February 2007
Date formatting in Python or in PostgreSQL (part II) 19 April 2006
Date formatting in python or in PostgreSQL 20 July 2004