Javascript 解析浮点数忽略逗号后的小数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7571553/
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:47:00  来源:igfitidea点击:

Javascript parse float is ignoring the decimals after my comma

javascriptparsefloat

提问by Only Bolivian Here

Here's a simple scenario. I want to show the subtraction of two values show on my site:

这是一个简单的场景。我想显示我网站上显示的两个值的减法:

//Value on my websites HTML is: "75,00"
var fullcost = parseFloat($("#fullcost").text()); 

//Value on my websites HTML is: "0,03"
var auctioncost = parseFloat($("#auctioncost").text());

alert(fullcost); //Outputs: 75
alert(auctioncost); //Ouputs: 0

Can anyone tell me what I'm doing wrong?

谁能告诉我我做错了什么?

回答by JaredPar

This is "By Design". The parseFloatfunction will only consider the parts of the string up until in reaches a non +, -, number, exponent or decimal point. Once it sees the comma it stops looking and only considers the "75" portion.

这是“按设计”。该parseFloat函数将只考虑字符串的部分,直到 in 到达非 +、-、数字、指数或小数点。一旦它看到逗号,它就会停止查找,只考虑“75”部分。

To fix this convert the commas to decimal points.

要解决此问题,请将逗号转换为小数点。

var fullcost = parseFloat($("#fullcost").text().replace(',', '.'));

回答by Joe

javascript's parseFloat doesn't take a locale parameter. So you will have to replace ,with .

javascript 的 parseFloat 不接受语言环境参数。所以你将不得不替换,.

parseFloat('0,04'.replace(/,/, '.')); // 0.04

回答by jamie

Why not use globalize? This is only one of the issues that you can run in to when you don't use the english language:

为什么不使用全球化?这只是您不使用英语时可能遇到的问题之一:

Globalize.parseFloat('0,04'); // 0.04

Some links on stackoverflow to look into:

stackoverflow 上的一些链接可以查看:

回答by T.J. Crowder

parseFloatparses according to the JavaScript definition of a decimal literal, not your locale's definition. (E.g., parseFloatis not locale-aware.) Decimal literals in JavaScript use .for the decimal point.

parseFloat根据十进制文字的 JavaScript定义进行解析,而不是您的语言环境定义。(例如,parseFloat不识别区域设置。)JavaScript 中的十进制文字.用于小数点。

回答by Michel Ayres

As @JaredPar pointed out in his answeruse parseFloatwith replace

正如@JaredPar 在他的回答中指出的那样使用parseFloat替换

var fullcost = parseFloat($("#fullcost").text().replace(',', '.'));

Just replacing the commawith a dotwill fix, Unlessit's a number over the thousands like 1.000.000,00this way will give you the wrong digit. So you need to replace the commaremove the dots.

只需用commaa替换即可dot修复,除非它是一个超过数千的数字,否则1.000.000,00会给您错误的数字。所以你需要更换comma删除dots

// Remove all dot's. Replace the comma.
var fullcost = parseFloat($("#fullcost").text().replace(/\./g,'').replace(',', '.'));

By using two replaces you'll be able to deal with the data without receiving wrong digits in the output.

通过使用两次替换,您将能够处理数据而不会在输出中收到错误的数字。

回答by Quentin

Numbers in JS use a .(full stop / period) character to indicate the decimal point not a ,(comma).

JS 中的数字使用.(句号/句点)字符来表示小数点而不是,(逗号)。

回答by mustapha mekhatria

It is better to use this syntax to replace all the commas in a case of a million 1,234,567

1,234,567 百万的情况下,最好使用此语法替换所有逗号

var string = "1,234,567";
string = string.replace(/[^\d\.\-]/g, ""); 
var number = parseFloat(string);
console.log(number)

The gmeans to remove all commas.

g方法删除所有逗号。

Check the Jsfiddle demo here.

此处查看Jsfiddle 演示

回答by DevShark

For anyone arriving here wondering how to deal with this problem where commas (,) and full stops (.) might be involved but the exact number format may not be known - this is how I correct a string before using parseFloat()(borrowing ideas from other answers):

对于到达这里想知道如何处理可能涉及逗号 ( ,) 和句号 ( .) 但确切的数字格式可能未知的问题的任何人 - 这就是我在使用之前更正字符串的方式parseFloat()(从其他答案中借用想法):

function preformatFloat(float){
   if(!float){
      return '';
   };

   //Index of first comma
   const posC = float.indexOf(',');

   if(posC === -1){
      //No commas found, treat as float
      return float;
   };

   //Index of first full stop
   const posFS = float.indexOf('.');

   if(posFS === -1){
      //Uses commas and not full stops - swap them (e.g. 1,23 --> 1.23)
      return float.replace(/\,/g, '.');
   };

   //Uses both commas and full stops - ensure correct order and remove 1000s separators
   return ((posC < posFS) ? (float.replace(/\,/g,'')) : (float.replace(/\./g,'').replace(',', '.')));
};
// <-- parseFloat(preformatFloat('5.200,75'))
// --> 5200.75

At the very least, this would allow parsing of British/American and European decimal formats (assuming the string contains a valid number).

至少,这将允许解析英国/美国和欧洲十进制格式(假设字符串包含有效数字)。

回答by Abel

From my origin country the currency format is like "3.050,89 "

从我的原籍国开始,货币格式类似于“3.050,89”

parseFloat identifies the dot as the decimal separator, to add 2 values we could put it like these:

parseFloat 将点标识为小数点分隔符,要添加 2 个值,我们可以这样写:

parseFloat(element.toString().replace(/\./g,'').replace(',', '.'))