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

后端 未结 19 2690
天涯浪人
天涯浪人 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 17:47

        $ 150.00
        Fr. 150.00
        € 689.00
    

    I have tested for above three currency symbols .You can do it for others also.

        var price = Fr. 150.00;
        var priceFloat = price.replace(/[^\d\.]/g, '');
    

    Above regular expression will remove everything that is not a digit or a period.So You can get the string without currency symbol but in case of " Fr. 150.00 " if you console for output then you will get price as

        console.log('priceFloat : '+priceFloat);
    
        output will be like  priceFloat : .150.00
    

    which is wrong so you check the index of "." then split that and get the proper result.

        if (priceFloat.indexOf('.') == 0) {
                priceFloat = parseFloat(priceFloat.split('.')[1]);
        }else{
                priceFloat = parseFloat(priceFloat);
        }
    

提交回复
热议问题