JavaScript provides the method parseInt to convert a numerical value into an integer, which is used to convert the string data "123" or the floating point number 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 Google version has been corrected
parseInt("1g"); // 1
parseInt("g1") ; // NaN
To do this, I wrote a function to convert 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 are also conversion functions written by netizens. They are also written down for reference. They are also suitable for converting data Convert to integer.
function toInt(number) {
return number && number | 0 || 0;
}
Note that the valid range of integers that the above two functions js can represent 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;
}
Statement:The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn