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

后端 未结 19 2674
天涯浪人
天涯浪人 2020-11-22 17:30

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,1

19条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-22 18:04

    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.

提交回复
热议问题