tags:

views:

188

answers:

4

I'd like to convert a money formatted string into a float in javascript.

ex: '$1,000.20' convert to a float 1000.20

'USD 1,000.20' convert to a float 1000.20

I'm also interested to know how to replace alphabetic characters to say '*'

How can this be implemented?

+1  A: 

Use JavaScript substring() Method to strip off letters and then parse using parseFloat

parseFloat('1,000.20')

parseFloat('1,000.20')
Xinus
+1  A: 

this could work:

floatstring=currencystring.replace(/\$/,"");
floatstring=floatstring.replace(/USD/,"");  
floatstring=floatstring.replace(/,/,"");  
floatstring=floatstring*1;
dusoft
+1 for replace function
Xinus
+1  A: 

Remove all non number symbols:

dirty_string.replace(/[^\d.]/g,'')

Oduvan
+2  A: 

You could pick out numbers from an arbitrary string with regex:

var match= string.match(/[0-9,.]*/);
if (match!==null) {
    var amount= parseFloat( match[0].replace(/,/g, '') ); // replace , thousands separator
}

However! It's generally a no-no to store money amounts in a floating point type due to the inaccuracy of floating point calculations. Of course JavaScript only gives you floating-point numbers, but by sticking to whole numbers (eg. of cents) you get accurate calculations up to the odd quadrillion.

Best of all for dealing with money is to use a decimal arithmetic type. This isn't a built-in type in JavaScript, but here's an implementation of it. (It is, unfortunately, rather heavyweight... I'm thinking of hacking up a simpler implementation of just the basics for trivial cases where you only need basic arithmetic.)

I'm also interested to know how to replace alphabetic characters to say '*'

regex again:

string.replace(/[A-Z]/gi, '*')

(for values of “alphabetic characters” within ASCII. If you need non-ASCII Unicode letters to be replaced you'd have to construct a much more involved character class... JavaScript doesn't have built-in classes for the metadata of the whole Unicode character set.)

bobince