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

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

    It's baffling that they included a toLocaleString but not a parse method. At least toLocaleString without arguments is well supported in IE6+.

    For a i18n solution, I came up with this:

    First detect the user's locale decimal separator:

    var decimalSeparator = 1.1;
    decimalSeparator = decimalSeparator.toLocaleString().substring(1, 2);
    

    Then normalize the number if there's more than one decimal separator in the String:

    var pattern = "([" + decimalSeparator + "])(?=.*\\1)";separator
    var formatted = valor.replace(new RegExp(pattern, "g"), "");
    

    Finally, remove anything that is not a number or a decimal separator:

    formatted = formatted.replace(new RegExp("[^0-9" + decimalSeparator + "]", "g"), '');
    return Number(formatted.replace(decimalSeparator, "."));
    

提交回复
热议问题