
Do you train Kung Fu?
Or know someone who does?
Then check out KungFuPeople.com
Mobile version of this page
Previous:
Earth, observed - The Big Picture - Boston.com
Next:
Nasty surprise of Django and gettext
Date formatting in Python or in PostgreSQL (part II)
Comparing REAL values in PostgreSQL
Earth, observed - The Big Picture - Boston.com
Next:
Nasty surprise of Django and gettext
Related blogs
Date formatting in python or in PostgreSQLDate formatting in Python or in PostgreSQL (part II)
Comparing REAL values in PostgreSQL
Related by category
Formatting numeric amounts in Javascript
16th of January 2009
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;
}
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";
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.


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