How to convert a currency string to a double with

2019-01-01 03:33发布

I have a text box that will have a currency string in it that I then need to convert that string to a double to perform some operations on it.

"$1,100.00" -> 1100.00

This needs to occur all client side. I have no choice but to leave the currency string as a currency string as input but need to cast/convert it to a double to allow some mathematical operations.

14条回答
与君花间醉酒
2楼-- · 2019-01-01 03:58

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;
查看更多
ら面具成の殇う
3楼-- · 2019-01-01 04:01
jQuery.preferCulture("en-IN");
var price = jQuery.format(39.00, "c");

output is: Rs. 39.00

use jquery.glob.js,
    jQuery.glob.all.js
查看更多
素衣白纱
4楼-- · 2019-01-01 04:03

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'));

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.

查看更多
皆成旧梦
5楼-- · 2019-01-01 04:03
var parseCurrency = function (e) {
    if (typeof (e) === 'number') return e;
    if (typeof (e) === 'string') {
        var str = e.trim();
        var value = Number(e.replace(/[^0-9.-]+/g, ""));
        return str.startsWith('(') && str.endsWith(')') ? -value: value;
    }

    return e;
} 
查看更多
大哥的爱人
6楼-- · 2019-01-01 04:08

Remove all non dot / digits:

var currency = "-$4,400.50";
var number = Number(currency.replace(/[^0-9.-]+/g,""));
查看更多
ら面具成の殇う
7楼-- · 2019-01-01 04:10

This example run ok

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

http://jsbin.com/ecAviVOV/2/edit

查看更多
登录 后发表回答