Convert String with Dot or Comma as decimal separator to number in JavaScript

后端 未结 11 769
时光取名叫无心
时光取名叫无心 2020-12-03 04:26

An input element contains numbers a where comma or dot is used as decimal separator and space may be used to group thousands like this:

\'1,2\'

11条回答
  •  时光说笑
    2020-12-03 04:45

    You could replace all spaces by an empty string, all comas by dots and then parse it.

    var str = "110 000,23";
    var num = parseFloat(str.replace(/\s/g, "").replace(",", "."));
    console.log(num);
    

    I used a regex in the first one to be able to match all spaces, not just the first one.

提交回复
热议问题