当我需要 500000 时,javascript parseFloat '500,000' 返回 500
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3205730/
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
javascript parseFloat '500,000' returns 500 when I need 500000
提问by DanC
How would it be a nice way of handling this?
如何处理这个问题的好方法?
I already thought on removing the comma and then parsing to float.
我已经考虑过删除逗号然后解析为浮动。
Do you know a better/cleaner way?
你知道更好/更清洁的方法吗?
Thanks
谢谢
采纳答案by Matchu
Nope. Remove the comma.
不。去掉逗号。
回答by James
parseFloat( theString.replace(/,/g,'') );
回答by micah
I don't know why no one has suggested this expression-
我不知道为什么没有人提出这种表达方式——
parseFloat( theString.replace(/[^\d\.]/g,'') );
Removes any non-numeric characters except for periods. You don't need custom functions/loops for this either, that's just overkill.
删除除句点以外的任何非数字字符。您也不需要为此自定义函数/循环,这太过分了。
回答by kennebec
You can use the string replace method, but not in a one liner as a regexp allows.
您可以使用字符串替换方法,但不能在正则表达式允许的单行中使用。
while(str.indexOf(',')!=-1)str= str.replace(',','');
parseFloat(str);
Or to make a single expression without a regexp=
或者制作一个没有正则表达式的单个表达式=
return parseFloat(str.split(',').join(''));
I'd use the regexp.
我会使用正则表达式。
回答by Mogzol
I don't have enough reputation to add a comment, but for anyone wondering on the performance for regex vs split/join, here's a quick fiddle: https://jsfiddle.net/uh3mmgru/
我没有足够的声誉来添加评论,但对于任何想知道 regex 与 split/join 性能的人来说,这里有一个快速的小提琴:https: //jsfiddle.net/uh3mmgru/
var test = "1,123,214.19";
var t0 = performance.now();
for (var i = 0; i < 1000000; i++)
{
var a = parseFloat(test.replace(/,/g,''));
}
var t1 = performance.now();
document.write('Regex took: ' + (t1 - t0) + ' ms');
document.write('<br>')
var t0 = performance.now();
for (var i = 0; i < 1000000; i++)
{
var b = parseFloat(test.split(',').join(''));
}
var t1 = performance.now();
document.write('Split/join took: ' + (t1 - t0) + ' ms');
The results I get are (for 1 million loops each):
我得到的结果是(每个循环 100 万次):
Regex: 263.335 ms
Split/join: 1035.875 ms
正则表达式:263.335 毫秒
拆分/加入:1035.875 毫秒
So I think its safe to say that regex is the way to go in this scenario
所以我认为可以肯定地说正则表达式是这种情况下的方法
回答by bradlis7
Building on the idea from @kennebec, if you want to make sure that the commas are correct, and you don't want to replace commas, you could try something like this:
基于@kennebec 的想法,如果您想确保逗号正确,并且不想替换逗号,您可以尝试以下操作:
function myParse(num) {
var n2 = num.split(",")
out = 0
for(var i = 0; i < n2.length; i++) {
out *= 1000;
out += parseFloat(n2[i])
}
return out
}
alert(myParse("1,432,85"));
// Returns 1432085, as the comma is misplaced.
It may not be as fast, but you wanted alternatives :)
它可能没有那么快,但你想要替代品:)
回答by Julio Marchi
What about a simple function to solve most of the common problems?
用一个简单的函数来解决大多数常见问题怎么样?
function getValue(obj) {
Value = parseFloat( $(obj).val().replace(/,/g,'') ).toFixed(2);
return +Value;
}
The above function gets values from fields (using jQuery) assuming the entered values are numeric (I rather validate fields while user is entering data, so I know for sure field content is numeric).
上面的函数从字段中获取值(使用 jQuery)假设输入的值是数字(我宁愿在用户输入数据时验证字段,所以我确定字段内容是数字)。
In case of floating point values, if well formatted in the field, the function will return a float point value correctly.
在浮点值的情况下,如果在字段中格式正确,该函数将正确返回浮点值。
This function is far from complete, but it quickly fix the "," (comma) issue for values entered as 1,234.56 or 1,234,567. It will return valid number as far the content is numeric.
此功能远未完成,但它可以快速修复输入为 1,234.56 或 1,234,567 的值的“ ,”(逗号)问题。只要内容是数字,它将返回有效数字。
The +(plus) sign in front of the variable Valuein the returncommand is a "dirty trick" used in JavaScript to assure the variable content returned will be numeric.
的+(加在变量的前面)标志值在返回命令是“脏特技在JavaScript用来保证返回将是可变内容”的数字。
it is easy to modify the function to other purposes, such as (for instance), convert strings to numeric values taking care of the "," (comma) issue:
很容易将函数修改为其他目的,例如(例如)将字符串转换为数值以解决“ ,”(逗号)问题:
function parseValue(str) {
Value = parseFloat( str.replace(/,/g,'') ).toFixed(2);
return +Value;
}
Both operations can even be combined in one function. I.e.:
这两种操作甚至可以合并为一个功能。IE:
function parseNumber(item,isField=false) {
Value = (isField) ? parseFloat( $(item).val().replace(/,/g,'') ).toFixed(2) : parseFloat( item.replace(/,/g,'') ).toFixed(2)
return +Value;
}
In such case, if function is called result = parseNumber('12,092.98');it will parse the value as it is a String. But if called as result = parseNumber('#MyField', true);it will try to obtain the value from '#MyField'.
在这种情况下,如果调用函数result = parseNumber('12,092.98'); 它将解析该值,因为它是一个字符串。但如果调用为result = parseNumber('#MyField', true); 它将尝试从'#MyField'获取值。
As I said before, such functions are far from complete, and can be expanded in many ways. One idea is to check the first character of the given parameter (string) and decide based on the string format where to obtain the value to be parsed (if 1st character is = '#'then it is an ID from a DOM object, otherwise, if it begins with a number, it must be a stringto be parsed).
前面说过,这样的功能还很不完善,可以通过多种方式进行扩展。一个想法是检查给定参数(字符串)的第一个字符,并根据字符串格式决定从哪里获取要解析的值(如果第一个字符是 = '#'则它是来自 DOM 对象的 ID,否则,如果以数字开头,则必须是要解析的字符串)。
Try it... Happy coding.
试试吧...快乐编码。

