Currency Conversion

N

News Guy

Hello,

Can someone tell me an easy way to convert a number with many trailing
digits to a currency format and adding the '$' sign? Thanks.

example

Convert 34.77389993 to $34.77

Thanks, News Guy
 
M

Michael Winter

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
 
R

Randy Webb

Danny said the following on 10/2/2005 2:08 AM:
Simple:

var aNum=34.77389993; formattedNum='$'+aNum.toFixed(2);

the '$' has to be string, then just use .toFixed() to limit the floating.

And then worry about the bugs in .toFixed()
 
D

Dr John Stockton

JRS: In article <[email protected]>, dated Mon, 3 Oct
2005 17:55:36, seen in News Guy
Can someone tell me an easy way to convert a number with many trailing
digits to a currency format and adding the '$' sign? Thanks.

Please read the newsgroup FAQ before asking about what is manifestly a
common need.

Numbers are binary, and don't have trailing digits; however, the default
conversion to String may give various non-zero numbers of digits after
the decimal point.

See <URL:http://www.merlyn.demon.co.uk/js-round.htm>
 
E

Evertjan.

News Guy wrote on 04 okt 2005 in comp.lang.javascript:
Thanks Danny, works great!

Testing in IE6:

var aNum=0.0094; formattedNum='$'+aNum.toFixed(2);

// gives 0.00

var aNum=34.0094; formattedNum='$'+aNum.toFixed(2);

// gives 34.01

Not so great, eh?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,995
Messages
2,570,226
Members
46,815
Latest member
treekmostly22

Latest Threads

Top