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

后端 未结 16 2593
被撕碎了的回忆
被撕碎了的回忆 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:37

    If you want to avoid the problem that David Meister posted and you are sure about the number of decimal places, you can replace all dots and commas and divide by 100, ex.:

    var value = "2,299.00";
    var amount = parseFloat(value.replace(/"|\,|\./g, ''))/100;
    

    or if you have 3 decimals

    var value = "2,299.001";
    var amount = parseFloat(value.replace(/"|\,|\./g, ''))/1000;
    

    It's up to you if you want to use parseInt, parseFloat or Number. Also If you want to keep the number of decimal places you can use the function .toFixed(...).

提交回复
热议问题