Formatting numeric amounts in Javascript

16 January 2009   1 comment   Javascript

Mind That Age!

This blog post is 9 years old! Most likely, its content is outdated. Especially if it's technical.

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.

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 by Keyword:
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
Related by Text:
jQuery and Highslide JS 08 January 2008
I'm back! Peterbe.com has been renewed 05 June 2005
Anti-McCain propaganda videos 12 August 2008
I'm Prolog 01 May 2007
Ever wondered how much $87 Billion is? 04 November 2003