如何在JavaScript中将字符串转换为整数?


当前回答

JavaScript中的字符串到数字:

一元+(最推荐)

+numStr易于使用,性能优于其他支持整数和小数

console.log(+'123.45') // => 123.45

其他一些选项:

正在分析字符串:

整数的parseInt(numStr)整数和小数的parseFloat(numStr)

console.log(parseInt('123.456')) // => 123
console.log(parseFloat('123'))   // => 123

JavaScript函数

整数的数学函数,如round(numStr)、floor(numStr)、ceil(numStr)整数和小数的数字(numStr)

console.log(Math.floor('123'))     // => 123
console.log(Math.round('123.456')) // => 123
console.log(Math.ceil('123.454'))  // => 124
console.log(Number('123.123'))     // => 123.123

单目运算符

所有基本一元运算符,+numStr、numStr-0、1*numStr,numStr*1和numStr/1所有都支持整数和小数注意numStr+0。它返回一个字符串。

console.log(+'123')  // => 123
console.log('002'-0) // => 2
console.log(1*'5')   // => 5
console.log('7.7'*1) // => 7.7
console.log(3.3/1)   // =>3.3
console.log('123.123'+0, typeof ('123.123' + 0)) // => 123.1230 string

位运算符

两个波浪号~~numStr或左移0,numStr<<0只支持整数,不支持小数

console.log(~~'123')      // => 123
console.log('0123'<<0)    // => 123
console.log(~~'123.123')  // => 123
console.log('123.123'<<0) // => 123

//正在分析console.log(parseInt('123.456'))//=>123console.log(parseFloat('123'))//=>123//功能console.log(数学楼层('123'))//=>123console.log(数学舍入('123.456'))//=>123console.log(数学.ceil('123.454'))//=>124console.log(编号('123.123'))//=>123.123//Unary公司console.log(+'123')//=>123console.log('002'-0)//=>2console.log(1*'5')//=>5console.log('7.7'*1)//=>7.7console.log(3.3/1)//=>3.3console.log('123.123'+0,typeof('123.123'+0))//=>123.1230字符串//按位(Bitwise)console.log(~~'123')//=>123console.log('0123'<<0)//=>123console.log(~~'123.123')//=>123console.log('123.123'<<0)//=>123

其他回答

尝试parseInt。

var number = parseInt("10", 10); //number will have value of 10.

最快的

var x = "1000"*1;

Test

这里有一些速度比较(仅限macOS)…:)

对于Chrome,“plus”和“mul”是最快的(>700000,00运算/秒),“Math.floor”是最慢的。对于Firefox,“plus”是最慢的(!)“mul”是最快的(>900000000操作/秒)。在Safari中,“parseInt”是最快的,“number”是最慢的(但结果非常相似,>130000<31000000)。因此Safari将字符串转换为int比其他浏览器慢10倍以上。所以获胜者是“mul”:)

您可以通过此链接在浏览器上运行它https://jsperf.com/js-cast-str-to-number/1

我还测试了var x=~~“1000”;。在Chrome和Safari上,它比var x=“1000”*1慢一点(<1%),在Firefox上则快一点(<1%)。

对于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;
}

这(可能)不是解析整数的最佳解决方案,但如果您需要“提取”一个整数,例如:

"1a2b3c" === 123
"198some text2hello world!30" === 198230
// ...

这将起作用(仅适用于整数):

var str='3a9b0c3d2e9f8g'函数提取器整数(str){var结果=0;无功因数=1对于(var i=str.length;i>0;i-){if(!isNaN(str[i-1])){result+=parseInt(str[i-1])*因子系数*=10}}返回结果}console.log(extractInteger(str))

当然,这也适用于解析整数,但比其他方法慢。

您也可以使用此方法解析整数,如果字符串不是数字,则返回NaN,但我不明白为什么要这样做,因为这在内部依赖于parseInt,parseInt可能更快。

var str='3a9b0c3d2e9f8g'函数提取器整数(str){var结果=0;无功因数=1对于(var i=str.length;i>0;i-){if(isNaN(str[i-1]))返回NaNresult+=parseInt(str[i-1])*因子系数*=10}返回结果}console.log(extractInteger(str))

在JavaScript中,您可以执行以下操作:

解析Int

parseInt("10.5") // Returns 10

与1相乘

var s = "10";
s = s*1;  // Returns 10

使用一元运算符(+)

var s = "10";
s = +s;  // Returns 10

使用按位运算符

(注:在2140000000之后开始破裂。示例:~~“2150000000”=-214967296)

var s = "10.5";
s = ~~s; // Returns 10

使用Math.floor()或Math.ceil()

var s = "10";
s = Math.floor(s) || Math.ceil(s); // Returns 10