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

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

    All of these answers fail if you have a number in the millions.

    3,456,789 would simply return 3456 with the replace method.

    The most correct answer for simply removing the commas would have to be.

    var number = '3,456,789.12';
    number.split(',').join('');
    /* number now equips 3456789.12 */
    parseFloat(number);
    

    Or simply written.

    number = parseFloat(number.split(',').join(''));
    

提交回复
热议问题