RE: Formatting Numbers using JavaScript

by "Cyanide _7" <leo7278(at)hotmail.com>

 Date:  Sat, 25 Mar 2000 05:14:42 CST
 To:  pbenoit(at)triton-network.com
 Cc:  hwg-languages(at)hwg.org
  todo: View Thread, Original
can't say much for simpler, but here is a shorter version that i wrote that 
includes commas as well as rounds to the nearest cent:

function format(num){
  if(isNaN(num))
    num = 0;
  var dol = Math.floor(num).toString();
  var cents = Math.floor((num*100+.5)%100).toString();
  for (var i = 0; i < Math.floor((dol.length-1)/3)-i; i++)
    dol = dol.slice(0,-(4*i+3))+','+dol.slice(-(4*i+3));
  while (cents.length<2)
    cents += "0";
  return "$"+dol+"."+cents;
}

- Cyanide_7

>
>I wasn't sure where I picked it up, if it was yours then thanks. ;)
>
>Lots of server side apps have much simpler solutions, php and cold fusion
>are two that come to mind.  Maybe one day Netscape, oops mean AOL, will 
>come
>up with a more elegant solution.  For now I'll just stick with ripping off
>David.  ;P
>
>Pete
>
> > -----Original Message-----
> > From:	David Mintz [SMTP:mambomintz(at)yahoo.com]
> > Sent:	Friday, March 24, 2000 2:17 PM
> > To:	hwg-languages(at)hwg.org
> > Subject:	RE: Formatting Numbers using JavaScript
> >
> > Well I'll be! That looks just like one I wrote with my
> > own hands and offered on the list some months ago. I'm
> > flattered.  Then someone else -- my apologies, I
> > forget your name -- proposed one that was more compact
> > and elegant. Wanna show it to us again? Every so often
> > we go through this -- how to format a number as
> > currency in Javascript. HWG oughta have a Javascript
> > FAQ or something.
> >
> > Notice how much easier it is with Perl (-: Yeah I
> > know, Javascript does it on the client side and it's
> > mighty fast, but people can disable javascript in
> > their browsers whereas they can hardly disable Perl on
> > your server.
> >
> > David Mintz
> > http://www.dmintzweb.com
> > http://www.panix.com/~dmintz
> >
> > --- Peter Benoit <pbenoit(at)triton-network.com> wrote:
> > > This is how I do it in Javascript:
> > >
> > > function format(num) {
> > > num = eval(num);
> > > num *= 100;
> > > num = Math.round(num)/100;
> > >
> > > 	if (num - Math.floor(num) == 0) {
> > > 		num = num + ".00";
> > > 	} else {
> > > 		string = num.toString();
> > > 		parts = string.split(".");
> > > 		cents = parts[1];
> > > 			if (cents.length == 1) {
> > > 				num = num + "0";
> > > 				}
> > > 	}
> > >
> > > num = "$" + num;
> > > return num;
> > > }
> > >
> >
> >
> > __________________________________________________
> > Do You Yahoo!?
> > Talk to your friends online with Yahoo! Messenger.
> > http://im.yahoo.com

______________________________________________________
Get Your Private, Free Email at http://www.hotmail.com

HWG: hwg-languages mailing list archives, maintained by Webmasters @ IWA