Convert string from money format to float in js
You can select numbers from an arbitrary string with a regex:
var match= string.match(/[0-9,.]*/);
if (match!==null) {
var amount= parseFloat( match[0].replace(/,/g, '') ); // replace , thousands separator
}
However! Typically, no-no for storing monetary amounts in floating point type due to the imprecision of floating point calculations. Of course JavaScript only gives floating point numbers, but by sticking to integers (like cents), you get accurate calculations down to an odd quadrillion.
The best way to deal with money is to use the decimal arithmetic type. It's not a built-in JavaScript type, but here 's an implementation . (This is, unfortunately, pretty heavyweight ... I'm thinking of hacking into a simpler implementation of just the basics for trivial cases where you only need basic arithmetic.)
I am also interested to know how to replace alphabetic characters to say '*'
regex again:
string.replace(/[A-Z]/gi, '*')
(for ASCII "literal character" values. If you need to replace non-ASCII Unicode letters, you have to build a much nicer character class ... JavaScript has no built-in metadata classes for the entire Unicode character set.)
source to share
A long time ago I made a regex to handle all kinds of currencies ...
([+-]?[0-9|^.|^,]+)[\.|,]([0-9]+)$
Look at the result
then you just need to get part of the share, delete all "." and "," and concat with part of the fraction, if it exists
End results:
let currency = "R$ -123.324,123,323"
let regex = /([+-]?[0-9|^.|^,]+)[\.|,]([0-9]+)$/igm
let result = regex.exec(currency);
console.log("Regex result: " + result);
let floatResult = result? result[1].replace(/[.,]/g, "")+ "." + result[2] : currency.replace(/[^0-9-+]/g, "");
console.log("Final result: " + floatResult);
Codepen: https://codepen.io/nicollaas94/pen/zdOevo?editors=0011
source to share
Use JavaScript substring () A way to trim letters and then parse with parseFloat
parseFloat('1,000.20')
parseFloat('1,000.20')
source to share