在 JavaScript / jQuery 中,将带逗号的数字转换为整数的最佳方法是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4083372/
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
In JavaScript / jQuery what is the best way to convert a number with a comma into an integer?
提问by David
I want to convert the string "15,678" into a value 15678. Methods parseInt()and parseFloat()are both returning 15 for "15,678." Is there an easy way to do this?
我想将字符串“15,678”转换为值 15678。方法parseInt()和parseFloat()都为“15,678”返回 15。是否有捷径可寻?
回答by SLaks
The simplest option is to remove all commas: parseInt(str.replace(/,/g, ''), 10)
最简单的选择是删除所有逗号: parseInt(str.replace(/,/g, ''), 10)
回答by paxdiablo
One way is to remove all the commas with:
一种方法是删除所有逗号:
strnum = strnum.replace(/\,/g, '');
and thenpass that to parseInt:
并且然后传递给parseInt函数:
var num = parseInt(strnum.replace(/\,/g, ''), 10);
But you need to be careful here. The use of commas as thousands separators is a cultural thing. In some areas, the number 1,234,567.89would be written 1.234.567,89.
但在这里你需要小心。使用逗号作为千位分隔符是一种文化。在某些地区,数字1,234,567.89会写成1.234.567,89。
回答by JustcallmeDrago
If you only have numbers and commas:
如果您只有数字和逗号:
+str.replace(',', '')
The +casts the string strinto a number if it can. To make this as clear as possible, wrap it with parens:
该+注塑字符串str,如果它可以转化为数字。为了尽可能清楚地说明这一点,请用括号将其包裹起来:
(+str.replace(',', ''))
therefore, if you use it in a statement it is more separate visually (+ +x looks very similar to ++x):
因此,如果您在语句中使用它,它在视觉上更加独立(++x 看起来与 ++x 非常相似):
var num = (+str1.replace(',', '')) + (+str1.replace(',', ''));
Javascript code conventions (See "Confusing Pluses and Minuses", second section from the bottom):
Javascript 代码约定(请参阅“令人困惑的优点和缺点”,从底部开始的第二部分):
回答by treeface
You can do it like this:
你可以这样做:
var value = parseInt("15,678".replace(",", ""));
回答by Nick Craver
Use a regex to remove the commas before parsing, like this
在解析之前使用正则表达式删除逗号,就像这样
parseInt(str.replace(/,/g,''), 10)
//or for decimals as well:
parseFloat(str.replace(/,/g,''))

