How can I parse a string with a comma thousand separator to a number?

后端 未结 16 2808
被撕碎了的回忆
被撕碎了的回忆 2020-11-22 10:18

I have 2,299.00 as a string and I am trying to parse it to a number. I tried using parseFloat, which results in 2. I guess the comma is the problem

16条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-22 10:48

    This converts a number in whatever locale to normal number. Works for decimals points too:

    function numberFromLocaleString(stringValue, locale){
        var parts = Number(1111.11).toLocaleString(locale).replace(/\d+/g,'').split('');
        if (stringValue === null)
            return null;
        if (parts.length==1) {
            parts.unshift('');
        }   
        return Number(String(stringValue).replace(new RegExp(parts[0].replace(/\s/g,' '),'g'), '').replace(parts[1],"."));
    }
    
    //Use default browser locale
    numberFromLocaleString("1,223,333.567") //1223333.567
    
    //Use specific locale
    numberFromLocaleString("1 223 333,567", "ru") //1223333.567
    

提交回复
热议问题