将带有点或逗号作为十进制分隔符的字符串转换为 JavaScript 中的数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7431833/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 02:14:35  来源:igfitidea点击:

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

javascriptjquerystring-parsingdata-conversion

提问by Andrus

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'
'110 000,23'
'100 1.23'

'1,2'
'110 000,23'
'100 1.23'

How would one convert them to a float number in the browser using JavaScript?

如何使用 JavaScript 在浏览器中将它们转换为浮点数?

jQuery and jQuery UI are used. Number(string)returns NaNand parseFloat()stops on first space or comma.

使用 jQuery 和 jQuery UI。Number(string)返回NaNparseFloat()在第一个空格或逗号处停止。

采纳答案by hytest

Do a replace first:

先做一个替换:

parseFloat(str.replace(',','.').replace(' ',''))

回答by Shafiq

The perfect solution

完美的解决方案

accounting.jsis a tiny JavaScript library for number, money and currency formatting.

accounting.js是一个用于数字、货币和货币格式的小型 JavaScript 库。

Check this for ref

检查这个以获取参考

回答by Thor84no

I realise I'm late to the party, but I wanted a solution for this that properly handled digit grouping as well as different decimal separators for currencies. As none of these fully covered my use case I wrote my own solution which may be useful to others:

我意识到我迟到了,但我想要一个解决方案来正确处理数字分组以及货币的不同小数分隔符。由于这些都没有完全涵盖我的用例,因此我编写了自己的解决方案,可能对其他人有用:

function parsePotentiallyGroupedFloat(stringValue) {
    stringValue = stringValue.trim();
    var result = stringValue.replace(/[^0-9]/g, '');
    if (/[,\.]\d{2}$/.test(stringValue)) {
        result = result.replace(/(\d{2})$/, '.');
    }
    return parseFloat(result);
}

This should strip out any non-digits and then check whether there was a decimal point (or comma) followed by two digits and insert the decimal point if needed.

这应该去掉任何非数字,然后检查是否有小数点(或逗号)后跟两位数字,并在需要时插入小数点。

It's worth noting that I aimed this specifically for currency and as such it assumes either no decimal places or exactly two. It's pretty hard to be sure about whether the first potential decimal point encountered is a decimal point or a digit grouping character (e.g., 1.542could be 1542) unless you know the specifics of the current locale, but it should be easy enough to tailor this to your specific use case by changing \d{2}$to something that will appropriately match what you expect to be after the decimal point.

值得注意的是,我专门针对货币进行了此操作,因此它假定没有小数位或恰好为两位。这是相当困难,以确保您所遇到的第一个潜在的小数点是一个小数点或数字分组字符(例如,1.542可能是1542),除非你知道当前区域的细节,但它应该是很容易的裁缝给你的通过更改\d{2}$为与您期望的小数点后的内容适当匹配的特定用例。

回答by Alex Turpin

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.

我在第一个中使用了正则表达式来匹配所有空格,而不仅仅是第一个。

回答by stuartchaney

This is the best solution

这是最好的解决方案

http://numeraljs.com/

http://numeraljs.com/

numeral().unformat('0.02'); = 0.02

回答by lpinto.eu

What about:

关于什么:

parseFloat(str.replace(' ', '').replace('.', '').replace(',', '.'));

回答by Slawa

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.

欢迎提出建议。

回答by niceblue

Here's a self-sufficient JS function that solves this (and other) problems for most European/US locales (primarily between US/German/Swedish number chunking and formatting ... as in the OP). I think it's an improvement on (and inspired by) Slawa's solution, and has no dependencies.

这是一个自给自足的 JS 函数,它解决了大多数欧洲/美国语言环境的这个(和其他)问题(主要在美国/德国/瑞典数字分块和格式之间......如在 OP 中)。我认为这是对 Slawa 解决方案的改进(并受其启发),并且没有依赖性。

function realParseFloat(s)
{
    s = s.replace(/[^\d,.-]/g, ''); // strip everything except numbers, dots, commas and negative sign
    if (navigator.language.substring(0, 2) !== "de" && /^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/.test(s)) // if not in German locale and matches #,###.######
    {
        s = s.replace(/,/g, ''); // strip out commas
        return parseFloat(s); // convert to number
    }
    else if (/^-?(?:\d+|\d{1,3}(?:\.\d{3})+)(?:,\d+)?$/.test(s)) // either in German locale or not match #,###.###### and now matches #.###,########
    {
        s = s.replace(/\./g, ''); // strip out dots
        s = s.replace(/,/g, '.'); // replace comma with dot
        return parseFloat(s);
    }
    else // try #,###.###### anyway
    {
        s = s.replace(/,/g, ''); // strip out commas
        return parseFloat(s); // convert to number
    }
}

回答by josgall

try this...

尝试这个...

var withComma = "23,3";
var withFloat = "23.3";

var compareValue = function(str){
  var fixed = parseFloat(str.replace(',','.'))
  if(fixed > 0){
      console.log(true)
    }else{
      console.log(false);
  }
}
compareValue(withComma);
compareValue(withFloat);

回答by bcody

Here is my solution that doesn't have any dependencies:

这是我的解决方案,没有任何依赖项:

return value
  .replace(/[^\d\-.,]/g, "")   // Basic sanitization. Allows '-' for negative numbers.
  .replace(",", ".")           // Change all commas to periods.
  .replace(/\.(?=.*\.)/g, ""); // Remove all periods except the last one.

(I left out the conversion to a number - that's probably just a parseFloat call if you don't care about JavaScript's precision problems with floats.)

(我省略了对数字的转换——如果你不关心 JavaScript 的浮点精度问题,那可能只是一个 parseFloat 调用。)

The code assumes that:

该代码假设:

  • Only commas and periods are used as decimal separators. (I'm not sure if locales exist that use other ones.)
  • The decimal part of the string does not use any separators.
  • 只有逗号和句点用作小数点分隔符。(我不确定是否存在使用其他语言环境的语言环境。)
  • 字符串的小数部分不使用任何分隔符。