Software, your way.
How To Get Good Custom Software
(Download)
(PDF)
burger menu icon
WillMaster

WillMaster > LibraryWebsite Owner Tools

FREE! Coding tips, tricks, and treasures.

Possibilities weekly ezine

Get the weekly email website developers read:

 

Your email address

name@example.com
YES! Send Possibilities every week!

Currency Formatting

Many web pages and documents publish currency amounts. Shopping cart items and totals, for example, and invoices.

Some numbers need conversion to the proper currency format. Examples are totals from adding item prices and calculated sales tax, numbers from a database, and numbers provided in a form.

As an example of use, existing software that adds those totals and calculates taxes and shipping charges can be modified to incorporate one of the two functions presented in this article for converting the result into currency format.

One of the functions is JavaScript and the other is PHP. Use whichever is applicable for your project.

Different currencies use different characters to show groups of thousands and the decimal part. With US Dollars, it's a comma and a period (as in 1,234.56). The functions in this article let you specify which characters to use. Also the number of decimal places for the currency.

If you want to study the nitty-gritty of formating for various currencies, see this currency internationalization page.

The functions presented in this article don't try to format for every currency. But most can be formatted.

Both functions do the same work. They have the same function name and similar variable names. The three customizable variables are spelled the same, except the variables in PHP begin with a "$" character.

When a number has more decimals than the currency format, it rounds the currency decimal.

When you know how to use one you also know how to use the other.

It's simple to implement and simple to use.

Try it here by typing in a number. It responds with USD currency formatting. (Specify other formatting in the source code of the function for other currency.)

Type a number:
Currency formatted: $

Put the function into the source code of your web page and update the three customizable variables. Then use the function by calling it with the number you want formatted.

Print the returned value or use it elsewhere in your code.

Here are the similarities and differences of the functions, one for JavaScript and one for PHP. (The source code with notes follow the tables.)

The JavaScript Function
Function name CurrencyFormat()
Number of source code lines 31
Variable to specify number of decimal places decimalplaces
Variable to specify the decimal character decimalcharacter
Variable to specify thousands group separater thousandseparater
The PHP Function
Function name CurrencyFormat()
Number of source code lines 7
Variable to specify number of decimal places $decimalplaces
Variable to specify the decimal character $decimalcharacter
Variable to specify thousands group separater $thousandseparater

The Source Code

Here's the source code for the JavaScript function. Implementation and use notes follow.

<script type="text/javascript">
function CurrencyFormat(number)
{
   var decimalplaces = 2;
   var decimalcharacter = ".";
   var thousandseparater = ",";
   number = parseFloat(number);
   var sign = number < 0 ? "-" : "";
   var formatted = new String(number.toFixed(decimalplaces));
   if( decimalcharacter.length && decimalcharacter != "." ) { formatted = formatted.replace(/\./,decimalcharacter); }
   var integer = "";
   var fraction = "";
   var strnumber = new String(formatted);
   var dotpos = decimalcharacter.length ? strnumber.indexOf(decimalcharacter) : -1;
   if( dotpos > -1 )
   {
      if( dotpos ) { integer = strnumber.substr(0,dotpos); }
      fraction = strnumber.substr(dotpos+1);
   }
   else { integer = strnumber; }
   if( integer ) { integer = String(Math.abs(integer)); }
   while( fraction.length < decimalplaces ) { fraction += "0"; }
   temparray = new Array();
   while( integer.length > 3 )
   {
      temparray.unshift(integer.substr(-3));
      integer = integer.substr(0,integer.length-3);
   }
   temparray.unshift(integer);
   integer = temparray.join(thousandseparater);
   return sign + integer + decimalcharacter + fraction;
}
</script>

JavaScript Function Implementation and Use Notes

Paste the JavaScript anywhere in the source code of your web page where JavaScript can run. Update the 3 customization variables:

  1. var decimalplaces = 2; If needed, change the number 2 for the number of decimal places the currency formatting required. (The number 0 is acceptable.)

  2. var decimalcharacter = "."; If needed, replace the period between the quotation marks with another character. The character separates the whole number from the decimal. For no decimal character, remove the period.

  3. var thousandseparater = ","; If needed, change the comma between the quotation marks. The character (which may be a space) will separate the groups of thousands. For no separation, remove the comma.

To use the function, call it with the number to be currency formatted. Here's an example, which stores a currency format in the variable amount. It's followed by three ways the variable amount can be used.

var amount = CurrencyFormat(12345.6789);

alert(amount+" USD"); // Alert box with a space and currency code appended to amount.
document.write("<b>amount+" USD</b>"); // Print amount with space and currency code appended.
document.getElementById("DivOrSpanIDvalue").innerHTML = amount; // Update content of an HTML container tag with amount.

Here's the source code for the PHP function. Implementation and use notes follow.

<?php
function CurrencyFormat($number)
{
   $decimalplaces = 2;
   $decimalcharacter = '.';
   $thousandseparater = ',';
   return number_format($number,$decimalplaces,$decimalcharacter,$thousandseparater);
}
?>

PHP Function Implementation and Use Notes

Paste the PHP anywhere in the source code of your web page where PHP can run. Update the 3 customization variables:

  1. $decimalplaces = 2; If needed, change the number 2 for the number of decimal places the currency formatting required. (The number 0 is acceptable.)

  2. $decimalcharacter = '.'; If needed, replace the period between the quotation marks with another character. The character separates the whole number from the decimal. For no decimal character, remove the period.

  3. $thousandseparater = ','; If needed, change the comma between the quotation marks. The character (which may be a space) will separate the groups of thousands. For no separation, remove the comma.

To use the function, call it with the number to be currency formatted. Here's an example, which stores a currency format in the variable $amount. It's followed by three ways the variable $amount can be used.

$amount = CurrencyFormat(12345.6789);

echo '<b>$' . $amount . ' USD</b>'; // Print the amount with currency symbol and currency code designations, bolded.
$list[] = $amount; // Store $amount to an array $list for later use.
echo '<tr><td>'.implode('</td><td>',$list).'</td></tr>'; // Print a row of table data with currency amounts stored in $list.

Both the JavaScript and PHP versions of the currency formatting function can return the format of most currencies in use today.

(This article first appeared in Possibilities ezine.)

Will Bontrager

Was this article helpful to you?
(anonymous form)

Support This Website

Some of our support is from people like you who see the value of all that's offered for FREE at this website.

"Yes, let me contribute."

Amount (USD):

Tap to Choose
Contribution
Method

All information in WillMaster Library articles is presented AS-IS.

We only suggest and recommend what we believe is of value. As remuneration for the time and research involved to provide quality links, we generally use affiliate links when we can. Whenever we link to something not our own, you should assume they are affiliate links or that we benefit in some way.

How Can We Help You? balloons
How Can We Help You?
bullet Custom Programming
bullet Ready-Made Software
bullet Technical Support
bullet Possibilities Newsletter
bullet Website "How-To" Info
bullet Useful Information List

© 1998-2001 William and Mari Bontrager
© 2001-2011 Bontrager Connection, LLC
© 2011-2024 Will Bontrager Software LLC