Convert string from money format to float in js

I would like to convert a money formatted string to float in javascript.

eg: '$ 1,000.20' convert to float 1000.20

'USD 1,000.20' convert to float 1000.20

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

How can this be done?

+2


source to share


6 answers


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.)

+5


source


Remove all non-numeric characters:



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

+4


source


A long time ago I made a regex to handle all kinds of currencies ...

([+-]?[0-9|^.|^,]+)[\.|,]([0-9]+)$

      

Look at the result

enter image description here

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

+2


source


Use JavaScript substring () A way to trim letters and then parse with parseFloat

parseFloat('1,000.20')

parseFloat('1,000.20')

      

+1


source


this might work:

floatstring=currencystring.replace(/\$/,"");
floatstring=floatstring.replace(/USD/,"");  
floatstring=floatstring.replace(/,/,"");  
floatstring=floatstring*1;

      

+1


source


This will remove all characters

      var value = string.replace(',', '');
      value = value.replace(/[^0-9,.]*/, '');
      value = parseFloat(value);

      

0


source







All Articles