Place your message here

Your Guide to Professional
Web Site Design and Development

Web Development
HTML Codes
HTML Tips
Javascript Snippets
216 Safe Colors
Symbols
Web Directory
Web Resources
Internet Channels

Web Development: Business, Advertising, Internet Marketing, Promotion and Web Site Design

| Web Development | HTML Codes | HTML Tips | Javascript Snippets | 216 Safe Colors | Symbols | Recommendations |

Use JavaScript to Format Currency within Your Web Page

By William Bontrager

This article will show you how to do two things:

     1. Round numbers to the nearest hundredth, with two
        digits following the decimal point. This can be
        useful when displaying prices or the totals of
        orders.

     2. Insert commas between every third digit (right to
        left) for numbers 1000 and larger. This can make
        numbers easier to read.

I'll show you how to do each of the above with both Perl and JavaScript. Links to a demonstration of each, and a link to download both, is at http://willmaster.com/a/18/pl.pl?art187

Currency Formatting

For United States dollars, and probably for most monetary units, an amount is expressed either as a whole number or as a fraction with two decimal places. The latter is the currency formatting discussed here.

     JavaScript --

Here is a JavaScript function to do currency formatting:

function CurrencyFormatted(amount)
{
	var i = parseFloat(amount);
	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;
}
// end of function CurrencyFormatted()

Give the function an amount and it will return that amount rounded to the nearest hundredth and with two digits following a decimal point.

First, the function stores the amount in variable i as a floating decimal point number, which means a number with a decimal point anywhere. It uses parseFloat() in case the function is sent a string representing a number instead of the number itself.

The next line checks to see whether or not there is actually a number to work with. Sending the function the value "hello" would result in a non-number. When that is the case, the function converts the non-number into "0.00"

After that, the function determines whether the number is positive or negative, converts it to positive if necessary, and rounds the number to the nearest hundredths.

Last, it makes sure there are two digits following the decimal point, prepends the "-" character if it started as a negative number, and returns the result.

You would call the function with something like this:

var result = CurrencyFormatted(number);


   Perl --

Here is a Perl function to do currency formatting:

sub CurrencyFormatted
{
	my $n = shift;
	my $minus = $n < 0 ? '-' : '';
	$n = abs($n);
	$n = int(($n + .005) * 100) / 100;
	$n .= '.00' unless $n =~ /\./;
	$n .= '0' if substr($n,(length($n) - 2),1) == '.';
	chop $n if $n =~ /\.\d\d0$/;
	return "$minus$n";
}
# end of subroutine CurrencyFormatted

Give the subroutine an amount and it will return that amount rounded to the nearest hundredth and with two digits following a decimal point.

Unlike the JavaScript, no special code had to be written to store the amount as a floating point number. Perl converts between strings and numbers, automatically. Also, when a number is needed, and a string doesn't readily convert to a number, the number zero is assumed.

The Perl subroutine does the job the JavaScript function does -- work with negative numbers as needed, rounds the number to the nearest hundredths, makes sure there are two digits following the decimal point, and returns the result.

You would call the subroutine with something like this:

my $result = CurrencyFormatted($number);

Putting Commas In Numbers

For ridiculously large numbers, like Bill Gate's financial worth, the number is easier to read when offset with a comma every three digits. Even smaller numbers can benefit in that way. For example, 8,888,888 is easier to comprehend than is 8888888.

The convention in some countries and regions is to use a period, a space, or other character instead of a comma. I'll note where to change the code for an alternate character.

     JavaScript --

Here is a JavaScript function to do comma formatting:

function CommaFormatted(amount)
{
	var delimiter = ","; // replace comma if desired
	var a = amount.split('.',2)
	var d = a[1];
	var i = parseInt(a[0]);
	if(isNaN(i)) { return ''; }
	var minus = '';
	if(i < 0) { minus = '-'; }
	i = Math.abs(i);
	var n = new String(i);
	var a = [];
	while(n.length > 3)
	{
		var nn = n.substr(n.length-3);
		a.unshift(nn);
		n = n.substr(0,n.length-3);
	}
	if(n.length > 0) { a.unshift(n); }
	n = a.join(delimiter);
	if(d.length < 1) { amount = n; }
	else { amount = n + '.' + d; }
	amount = minus + amount;
	return amount;
}
// end of function CommaFormatted()

Near the top of the function, the variable delimiter is assigned the comma character. That's the comma between the quotation marks. To use a different delimiter, change the comma character to the character of your choice.

The function splits the amount on the decimal point if the amount has a decimal point. The digits following the decimal point, if any, are stored in variable d.

The number in front of the decimal point, if any, or the entire amount, is stored as an integer in variable i. If i is not a number, the function returns a null value.

Negative numbers are handled similar to the currency conversion function.

Next, three digits are removed from the end of the number and assigned to array variable a, so long as the number is longer than three digits. The number is then reformed using the elements of array a, with the delimiter digit inserted between each element.

Last, the decimal portion is appended to the number and the minus sign put in front, if appropriate, and the number returned.

You would call the function with something like this:

var result = CommaFormatted(number);


     Perl --

Here is a Perl function to do comma formatting:

sub CommaFormatted
{
	my $delimiter = ','; # replace comma if desired
	my($n,$d) = split /\./,shift,2;
	my @a = ();
	while($n =~ /\d\d\d\d/)
	{
		$n =~ s/(\d\d\d)$//;
		unshift @a,$1;
	}
	unshift @a,$n;
	$n = join $delimiter,@a;
	$n = "$n\.$d" if $d =~ /\d/;
	return $n;
}
# end of subroutine CommaFormatted

Near the top of the subroutine, the variable $delimiter is assigned the comma character. That's the comma between the apostrophes. To use a different delimiter, change the comma character to the character of your choice.

The Perl subroutine does the job the JavaScript function does -- split on the decimal point, move three digits from the number into array @a so long as the number is more than three digits long, reform the number with the $delimiter character between the elements, attach the decimal and minus characters if needed, and returns the result.

You would call the subroutine with something like this:

my $result = CommaFormatted($number);

Using the Code

The demonstration (URL above) show one way to use the JavaScript functions and Perl subroutines. Please feel free to use them in the programs you write and modify. Simply call the relevant function or subroutine in the manner indicated and it will format the amount for you. They can be used together, if desired.

For JavaScript these two lines could do the job:

var result = CurrencyFormatted(number);
result = CommaFormatted(result);

First, the number is converted to currency format and stored in variable result. Then, result is converted to comma format and stored in the same variable result.

For Perl, this one line could do the job:

my $result = CommaFormatted(CurrencyFormatted($number));

First, $number is converted to currency format, which is then immediately converted to comma format, which is then stored in the variable $result.

Will Bontrager

About the Author:

William Bontrager Programmer/Publisher, "WillMaster Possibilities" ezine mailto:possibilities@willmaster.com

Are you looking for top quality scripts? Visit Willmaster and check out his highly acclaimed Master Series scripts. Some free, some for a fee.

Back