...

View Full Version : Javascript Multiple number WITH dollar sign and comma.



jpater74
12-12-2007, 08:54 AM
I'm new to this group. Hello!

I'm having some trouble.

I have a variable that is coming in and it has a dollar sign and a comma in it.

For example

The variable is called tmp_price.

So lets say the amount is $350,000, how do I multiply it by .96? Javascipt blows up with the $ sign

So I have this simple code:
<SCRIPT Language = JavaScript>
B = 100
D = (B * .96)
document.write(D)
</SCRIPT>

Which will produce: 96

But if I replace "100" with tmp_price and that tmp_price is $350,000 I get an error.

So how to I do a simple equation to multiply .96 time this variable with a dollar and comma in it.

Thanks

JP

oesxyl
12-12-2007, 09:16 AM
you can use regex:

http://www.javascriptkit.com/jsref/regexp.shtml

to extract only the price, unformated, and to check if it's valid.

Example:

price = '$110,210';
price.replace(/\D/g,'');

to work with price as '$10.50', you must first split this string in two parts'
'$10' and '50' and join it after processing.

best regards

felgall
12-12-2007, 09:23 AM
A decimal point is allwed in a number, you just need to use a regular expression to get rid of the dollar sign and commas. It may be easier to just strip out everything that is not numeric.


var num = '$500.04';
num = num.replace(/[\D\.-]+/g,'')-0;
alert(num);

Oh and if you want to put the currency symbol and commas back later see http://javascript.about.com/library/blnumfmt.htm

oesxyl
12-12-2007, 09:29 AM
A decimal point is allwed in a number, you just need to use a regular expression to get rid of the dollar sign and commas. It may be easier to just strip out everything that is not numeric.


var num = '$500.04';
num = num.replace(/[\D\.]+/g,'')-0;
alert(num);

what if num = '$500' without '.'?

jpater74
12-12-2007, 11:17 PM
Awesome oesxyl, that worked great!



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum