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

后端 未结 19 2480
天涯浪人
天涯浪人 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:01

    This is my function. Works with all currencies..

    function toFloat(num) {
        dotPos = num.indexOf('.');
        commaPos = num.indexOf(',');
    
        if (dotPos < 0)
            dotPos = 0;
    
        if (commaPos < 0)
            commaPos = 0;
    
        if ((dotPos > commaPos) && dotPos)
            sep = dotPos;
        else {
            if ((commaPos > dotPos) && commaPos)
                sep = commaPos;
            else
                sep = false;
        }
    
        if (sep == false)
            return parseFloat(num.replace(/[^\d]/g, ""));
    
        return parseFloat(
            num.substr(0, sep).replace(/[^\d]/g, "") + '.' + 
            num.substr(sep+1, num.length).replace(/[^0-9]/, "")
        );
    
    }
    

    Usage : toFloat("$1,100.00") or toFloat("1,100.00$")

提交回复
热议问题