[thelist] Adding extra zeros to dollar amounts when neccesary

David Bindel dbindel at austin.rr.com
Wed Feb 26 02:20:01 CST 2003


-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

> Would anyone be able to outline a method (in ECMA/javascript
> ideally) by which I could add extra zeros to a numeric value
> to display a dollar amount correctly?
>
> Example: 5 into 5.00

It's been a few years since I've done any client-side scripting, but
I do PHP and C++ regularly, so I remember some of the Javascript I
used to know.  Below is the one-line function (using the ternary
operator!) I just wrote and tested.


function add_zeros(orig_num) {
	return orig_num + (orig_num.indexOf('.') == -1) ? ".00" : "";
}


The way it works:

First, it checks to see whether or not the "number" (in actuality, it
is a string) contains a ".".  If it contains a ".", nothing is
changed and the original value is returned.  If it does not contain a
".", the string ".00" is appended to the returned value.

How to use it:

document.write(add_zeros("5")); // outputs "5.00"
document.write(add_zeros("5.00")); //outputs "5.00"
Document.write(add_zeros("5.")); outputs "5."
document.write(add_zeros("Hello, World!")); // outputs "Hello,
World!.00"

The only "bugs" you might find with the function are if you pass
either 1) it a string containing non-numeral data (i.e. letters,
words, and special characters), or 2) malformed data (i.e. "5.").
Obviously, this kind of data isn't even meant to be used with the
function, so that should not be a problem as long as you write your
own code well.  [If it is used, it will still perform the "." check,
so if the string you pass it ("Hello, World!", for example) doesn't
have a ".", it will return the string with the ".00" appended to the
end ("Hello, World!.00").]

Best of luck,
David Bindel

-----BEGIN PGP SIGNATURE-----
Version: PGP 7.0.4

iQA/AwUBPlx43H6TtTuKuQdTEQKp4gCdGrghTRBlrVKFQcAh7ZUUpjaZL2MAnAmg
mfT2lbJ/CiOnMkRpffT4mtg5
=0ltd
-----END PGP SIGNATURE-----




More information about the thelist mailing list