Formatting numeric amounts in Javascript

16 January 2009   1 comment   Javascript

Mind That Age!

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

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 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:
Interesting float/int casting in Python 25 April 2006
json-schema-reducer 02 August 2016
String length truncation optimization difference in Python 19 March 2012
Best non-cryptographic hashing function in Python (size and speed) 21 February 2015
Fastest *local* cache backend possible for Django 04 August 2017