如何在JavaScript中将字符串转换为整数?
当前回答
在我看来,没有答案涵盖所有边缘情况,因为解析浮点值会导致错误。
function parseInteger(value) {
if(value === '') return NaN;
const number = Number(value);
return Number.isInteger(number) ? number : NaN;
}
parseInteger("4") // 4
parseInteger("5aaa") // NaN
parseInteger("4.33333") // NaN
parseInteger("aaa"); // NaN
其他回答
如果您使用parseInt将浮点转换为科学符号,请小心!例如:
parseInt("5.6e-14")
将导致
5
而不是
0
我只在字符串前加了一个加号(+),这就是解决方案!
+"052254" // 52254
请参见以下示例。这将有助于回答您的问题。
Example Result
parseInt("4") 4
parseInt("5aaa") 5
parseInt("4.33333") 4
parseInt("aaa"); NaN (means "Not a Number")
通过使用parsent函数,它将只提供整数运算,而不提供字符串。
函数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>
对于C和JavaScript之间的绑定,我实际上需要将字符串“保存”为整数,因此我将字符串转换为整数值:
/*
Examples:
int2str( str2int("test") ) == "test" // true
int2str( str2int("t€st") ) // "t¬st", because "€".charCodeAt(0) is 8364, will be AND'ed with 0xff
Limitations:
maximum 4 characters, so it fits into an integer
*/
function str2int(the_str) {
var ret = 0;
var len = the_str.length;
if (len >= 1) ret += (the_str.charCodeAt(0) & 0xff) << 0;
if (len >= 2) ret += (the_str.charCodeAt(1) & 0xff) << 8;
if (len >= 3) ret += (the_str.charCodeAt(2) & 0xff) << 16;
if (len >= 4) ret += (the_str.charCodeAt(3) & 0xff) << 24;
return ret;
}
function int2str(the_int) {
var tmp = [
(the_int & 0x000000ff) >> 0,
(the_int & 0x0000ff00) >> 8,
(the_int & 0x00ff0000) >> 16,
(the_int & 0xff000000) >> 24
];
var ret = "";
for (var i=0; i<4; i++) {
if (tmp[i] == 0)
break;
ret += String.fromCharCode(tmp[i]);
}
return ret;
}