如何在JavaScript中将字符串转换为整数?
当前回答
前面的所有答案都是正确的。请先通过“typeot x==='number'”确认这是字符串中的数字。否则,它将返回NaN。
var num = "fsdfsdf242342";
typeof num => 'string';
var num1 = "12423";
typeof num1 => 'number';
+num1 = > 12423`
其他回答
我们可以使用+(stringOfNumber)而不是parseInt(stringOfNumber)。
示例:+(“21”)返回int值为21,类似于parseInt(“21)。
我们也可以使用这个一元“+”运算符来解析浮点数。。。
请参见以下示例。这将有助于回答您的问题。
Example Result
parseInt("4") 4
parseInt("5aaa") 5
parseInt("4.33333") 4
parseInt("aaa"); NaN (means "Not a Number")
通过使用parsent函数,它将只提供整数运算,而不提供字符串。
最简单的方法是这样使用+
const strTen = "10"
const numTen = +strTen // string to number conversion
console.log(typeof strTen) // string
console.log(typeof numTen) // number
如果您使用parseInt将浮点转换为科学符号,请小心!例如:
parseInt("5.6e-14")
将导致
5
而不是
0
函数doSth(){var a=document.getElementById('input').value;document.getElementById('number').innerHTML=toNumber(a)+1;}函数toNumber(str){return+str;}<input id=“input”type=“text”><input onclick=“doSth()”type=“submit”><span id=“number”></span>