In JavaScript / jQuery what is the best way to convert a number with a comma into an integer?

风格不统一 提交于 2019-11-27 15:42:51

问题


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?


回答1:


The simplest option is to remove all commas: parseInt(str.replace(/,/g, ''), 10)




回答2:


One way is to remove all the commas with:

strnum = strnum.replace(/\,/g, '');

and then pass that to 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.89 would be written 1.234.567,89.




回答3:


If you only have numbers and commas:

+str.replace(',', '')

The + casts the string str into a number if it can. To make this as clear as possible, wrap it with parens:

(+str.replace(',', ''))

therefore, if you use it in a statement it is more separate visually (+ +x looks very similar to ++x):

var num = (+str1.replace(',', '')) + (+str1.replace(',', ''));

Javascript code conventions (See "Confusing Pluses and Minuses", second section from the bottom):

http://javascript.crockford.com/code.html




回答4:


You can do it like this:

var value = parseInt("15,678".replace(",", ""));



回答5:


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,''))

You can test it here.



来源:https://stackoverflow.com/questions/4083372/in-javascript-jquery-what-is-the-best-way-to-convert-a-number-with-a-comma-int

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!