Kwissle

My real-time quiz battle game Kwissle.com

Crosstips.org

My fun Crossword solver project. Crosstips.org & Krysstips.se

Kung Fu

Fujian White Crane Kung Fu

Photos

Photoalbum, both old and new.

Twitter

Follow me on Twitter

Contact me

My contact details and how to contact me.

 

KungFuPeople.com
Do you train Kung Fu?
Or know someone who does?
Then check out KungFuPeople.com


Mobile version of this page Mobile version of this page


 
JavaScript

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;
 }

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.



Comment

djo - 16th January 2009  [«« Reply to this]
Google for "javascript sprintf" throws a few things up. More code, but at least printf format strings are pretty universal.
 
Name:
Email:
hide my email address.

Your email address will be encoded to prevent email-extraction spiders from reading it so you won't get spammed if you decide to show your email address.