简体   繁体   English

在JavaScript中将String转换为Integer

[英]Convert String to Integer in JavaScript

I have a string value of 41,123 and I want to convert it to an integer in JavaScript. 我有一个41,123的字符串值,我想在JavaScript中将其转换为整数。

I tried parseInt(41,123, 10) and parseFloat, but nothing gives me correct answer. 我试过parseInt(41,123,10)和parseFloat,但没有给我正确答案。

ParseInt, parseFloat work well until comma is encountered, but to above the result is '41'. ParseInt,parseFloat工作正常,直到遇到逗号,但结果为'41'。

Does anyone have an idea about the fix? 有没有人对修复有所了解?

var myInt = parseInt("41,123,10".replace(/,/g,""));

Here is the solution: 这是解决方案:

Number(s.replace(/,/g, ""))

Regex is needed in replacement to remove all comma characters, otherwise only one comma will be replaced. 需要使用正则表达式来删除所有逗号字符,否则只会替换一个逗号。

You can remove the comma, and then parse; 您可以删除逗号,然后解析; let's say the number is variable s : 假设数字是变量s

parseInt(s.replace(/,/g, '')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM