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

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

    Remove anything that isn't a digit, decimal point, or minus sign (-):

    var str = "2,299.00";
    str = str.replace(/[^\d\.\-]/g, ""); // You might also include + if you want them to be able to type it
    var num = parseFloat(str);
    

    Updated fiddle

    Note that it won't work for numbers in scientific notation. If you want it to, change the replace line to add e, E, and + to the list of acceptable characters:

    str = str.replace(/[^\d\.\-eE+]/g, "");
    

提交回复
热议问题