Advertisement

02.07.2008 at 10:42AM PST, ID: 23145397
[x]
Attachment Details

Format currency in javascript

Asked by michael1174 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.

Start Free Trial
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
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);
	}
 
}
 
Loading Advertisement...
 
[+][-]02.07.2008 at 11:14AM PST, ID: 20843999

View this solution now by starting your 7-day free trial. Setting up your free trial is quick, easy, and secure. We will return you to this solution, unlocked, when you're done.

 

About this solution

Zone: JavaScript
Sign Up Now!
Solution Provided By: contactkarthi
Participating Experts: 1
Solution Grade: A
 
 
[+][-]02.07.2008 at 11:43AM PST, ID: 20844281

Often, when Experts are collaborating with members who have asked questions, they will request additional information about the problem. Askers respond with an author comment like this one.

Start your 7-day free trial to view this Author Comment or ask the Experts your question.

 
 
Loading Advertisement...
20080716-EE-VQP-32 / EE_QW_2_20070628