michael1174
asked on
Format currency in javascript
Experts,
I have a formatCurrency function that I need to enhance. I need it to be able to do the following:
If a user enters a H or h after a number, then multiply that number so it is formatted in the hundreds
If a user enters a T or t after a number, then multiply that number so it is formatted in the thousands
If a user enters a M or m after a number, then multiply that number so it is formatted in the milions
for example,
5m = 5,000,000
3T = 3,000
My function right now strips out characters. I need it to not strip out those characters mentioned above and format it.
I have a formatCurrency function that I need to enhance. I need it to be able to do the following:
If a user enters a H or h after a number, then multiply that number so it is formatted in the hundreds
If a user enters a T or t after a number, then multiply that number so it is formatted in the thousands
If a user enters a M or m after a number, then multiply that number so it is formatted in the milions
for example,
5m = 5,000,000
3T = 3,000
My function right now strips out characters. I need it to not strip out those characters mentioned above and format it.
function formatCurrency(fld, curPrefix) {
//Get rid of any thing other than numbers and decimal places.
if(fld.value == ""){
}
else
{
num = fld.value;
num = num.toString().replace(/[^0-9.]/g,'');
if(isNaN(num)) num = "0";
sign = (num == (num = Math.abs(num)));
num = Math.floor(num*100+0.50000000001);
cents = num%100;
num = Math.floor(num/100).toString();
if(cents<10) cents = "0" + cents;
for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++) {
num = num.substring(0,num.length-(4*i+3))+','+
num.substring(num.length-(4*i+3));
}
// Comment next line you do not want 2 decimal places.
//fld.value = ( ( (sign)?'':'-') + curPrefix + num + '.' + cents);
//return (((sign)?'':'-') + curPrefix + num + '.' + cents);
// UnComment next line you do not want 2 decimal places.
fld.value = (((sign)?'':'-') + curPrefix + num);
return (((sign)?'':'-') + curPrefix + num);
}
}
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Thanks, ingnore my comment below.. this works great!
it works great
<input type="text" name="myText1" onBlur="formatCurrency(thi s,'$')">
maybe you should have onBlur
B CAPS
<input type="text" name="myText1" onBlur="formatCurrency(thi
maybe you should have onBlur
B CAPS
ASKER
I am calling my function on the onblur event. Is that the right event?
onblur="formatCurrency(thi