Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a currency string to a double with Javascript?

People also ask

How to convert string to double in jQuery?

jQuery – Convert string to float or double Find code to convert String to float or double using jQuery. To convert, use JavaScript parseFloat() function parses a string and returns a floating point number. var sVal = '234.54'; var iNum = parseFloat(sVal); //Output will be 234.54.


Remove all non dot / digits:

var currency = "-$4,400.50";
var number = Number(currency.replace(/[^0-9.-]+/g,""));

Use a regex to remove the formating (dollar and comma), and use parseFloat to convert the string to a floating point number.`

var currency = "$1,100.00";
currency.replace(/[$,]+/g,"");
var result = parseFloat(currency) + .05;

accounting.js is the way to go. I used it at a project and had very good experience using it.

accounting.formatMoney(4999.99, "€", 2, ".", ","); // €4.999,99
accounting.unformat("€ 1.000.000,00", ","); // 1000000

You can find it at GitHub


I know this is an old question but wanted to give an additional option.

The jQuery Globalize gives the ability to parse a culture specific format to a float.

https://github.com/jquery/globalize

Given a string "$13,042.00", and Globalize set to en-US:

Globalize.culture("en-US");

You can parse the float value out like so:

var result = Globalize.parseFloat(Globalize.format("$13,042.00", "c"));

This will give you:

13042.00

And allows you to work with other cultures.


I know this is an old question, but CMS's answer seems to have one tiny little flaw: it only works if currency format uses "." as decimal separator. For example, if you need to work with russian rubles, the string will look like this: "1 000,00 rub."

My solution is far less elegant than CMS's, but it should do the trick.

var currency = "1 000,00 rub."; //it works for US-style currency strings as well
var cur_re = /\D*(\d+|\d.*?\d)(?:\D+(\d{2}))?\D*$/;
var parts = cur_re.exec(currency);
var number = parseFloat(parts[1].replace(/\D/,'')+'.'+(parts[2]?parts[2]:'00'));
console.log(number.toFixed(2));

Assumptions:

  • currency value uses decimal notation
  • there are no digits in the string that are not a part of the currency value
  • currency value contains either 0 or 2 digits in its fractional part *

The regexp can even handle something like "1,999 dollars and 99 cents", though it isn't an intended feature and it should not be relied upon.

Hope this will help someone.


This example run ok

var currency = "$1,123,456.00";
var number = Number(currency.replace(/[^0-9\.]+/g,""));
console.log(number);