JavaScript's method of converting data to integers

  • 2020-03-30 01:13:11
  • OfStack

JavaScript provides a method, parseInt, to convert numeric values to integers, to convert string data "123", or to floating-point Numbers 1.23.


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 always valid:


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

To do this, I wrote a function that converts arbitrary data into integers.


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(Number.NaN);  // 0
toInt(1/0);  // 0

There is a netizen write conversion function here, also write down to provide reference, also suitable for data into integer.

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

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

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


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


Related articles: