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

后端 未结 11 748
时光取名叫无心
时光取名叫无心 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:50

    All the other solutions require you to know the format in advance. I needed to detect(!) the format in every case and this is what I end up with.

    function detectFloat(source) {
        let float = accounting.unformat(source);
        let posComma = source.indexOf(',');
        if (posComma > -1) {
            let posDot = source.indexOf('.');
            if (posDot > -1 && posComma > posDot) {
                let germanFloat = accounting.unformat(source, ',');
                if (Math.abs(germanFloat) > Math.abs(float)) {
                    float = germanFloat;
                }
            } else {
                // source = source.replace(/,/g, '.');
                float = accounting.unformat(source, ',');
            }
        }
        return float;
    }
    

    This was tested with the following cases:

            const cases = {
                "0": 0,
                "10.12": 10.12,
                "222.20": 222.20,
                "-222.20": -222.20,
                "+222,20": 222.20,
                "-222,20": -222.20,
                "-2.222,20": -2222.20,
                "-11.111,20": -11111.20,
            };
    

    Suggestions welcome.

提交回复
热议问题