SoFunction
Updated on 2025-04-06

JavaScript method to convert data into integers

JavaScript provides a method parseInt to convert numeric values ​​into integers, which is used to convert string data "123" or floating point number 1.23.

Copy the codeThe code is as follows:

parseInt("1");  // 1
parseInt("1.2");  // 1
parseInt("-1.2");  // -1
parseInt(1.2);  // 1
parseInt(0);  // 0
parseInt("0");  // 0

But this parseInt function is not often valid:

Copy the codeThe code is as follows:

parseInt('06'); // 6
parseInt('08'); // 0  Note that Google's new version has been fixed
parseInt("1g"); // 1
parseInt("g1"); // NaN

To do this, I wrote a function to convert arbitrary data into integers.

Copy the codeThe code is as follows:

function toInt(number) {
    return number*1 | 0 || 0;
}

//test
toInt("1");  // 1
toInt("1.2");  // 1
toInt("-1.2");  // -1
toInt(1.2);  // 1
toInt(0);  // 0
toInt("0");  // 0
toInt();  // 0
toInt(1/0);  // 0

There are also conversion functions written by netizens here, which are also written down for reference, which is also suitable for converting data into integers.
Copy the codeThe code is as follows:

function toInt(number) {
    return number && + number | 0 || 0;
}

Note that the effective range of integers that can be represented by the above two functions js is -1569325056 ~ 1569325056

In order to express a larger range of numeric values ​​in js, I also wrote a function for reference, as follows:

Copy the codeThe code is as follows:

function toInt(number) {
    return Infinity === number ? 0 : (number*1 || 0).toFixed(0)*1;
}