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

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

    // "10.000.500,61 TL" price_to_number => 10000500.61

    // "10000500.62" number_to_price => 10.000.500,62

    JS FIDDLE: https://jsfiddle.net/Limitlessisa/oxhgd32c/

    var price="10.000.500,61 TL";
    document.getElementById("demo1").innerHTML = price_to_number(price);
    
    var numberPrice="10000500.62";
    document.getElementById("demo2").innerHTML = number_to_price(numberPrice);
    
    function price_to_number(v){
        if(!v){return 0;}
        v=v.split('.').join('');
        v=v.split(',').join('.');
        return Number(v.replace(/[^0-9.]/g, ""));
    }
    
    function number_to_price(v){
        if(v==0){return '0,00';}
        v=parseFloat(v);
        v=v.toFixed(2).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
        v=v.split('.').join('*').split(',').join('.').split('*').join(',');
        return v;
    }
    

提交回复
热议问题