On 03/10/2005 18:55, News Guy wrote:
Can someone tell me an easy way to convert a number with many trailing
digits to a currency format and adding the '$' sign? Thanks.
/* n - Number to format (in pennies).
* c - Currency symbol to use (defaults to none).
* g - Thousands symbol (defaults to none).
* d - Decimal separator (defaults to dot [.]).
*
* Outputs a number of the form cngnnngnnn.nn
*
* For example, toCurrency(142635.7, '£', ',') produces
* £1,426.36
*/
function toCurrency(n, c, g, d) {
var s = (0 > n) ? '-' : '';
var m = String(Math.round(Math.abs(n)));
var i = '', j, f; c = c || ''; g = g || ''; d = d || '.';
while(m.length < 3) {m = '0' + m;}
f = m.substring((j = m.length - 2));
while(j > 3) {
i = g + m.substring(j - 3, j) + i;
j -= 3;
}
i = m.substring(0, j) + i;
return s + c + i + d + f;
}
Take note of the arguments.
Mike
--
Michael Winter
Prefix subject with [News] before replying by e-mail.