Summary
I just thought of three methods for now. If readers think of other good methods, they can also communicate.
parseInt
bit operator
Math.floor Math.ceil
Description
1. parseInt
1. Example
parseInt("13nash");//13parseInt("")// NaNparseInt("0xA") //10(hexadecimal)parseInt("13")//13parseInt("070")//ES3 is 56(octal) ES5 is 70parseInt(070)// Both ES3 and ES5 are 56parseInt(22.5)//222. Conversion rules:
(1). According to example (1), parseInt will be parsed until it stops when non-number
(2). According to example (2), it is NaN when parsing an empty string, rather than 0
(3). According to Example (3), parseInt can convert hexadecimal numbers into decimal
(4). According to example (4), parseInt ignores the spaces of the string
3. Disadvantages:
(1). According to Example (5), we can know that parseInt is incompatible when converting octal arrays. ES3 will regard 070 as an octal value, but ES5 will regard 070 as a decimal.
(2). According to Example (6)(7) we can know that when parseInt is executed, it will first convert the parameter into a string and then execute it into an integer
4. Explanation: Why (5)(6) executions convert 070 into integers, but the results are different? This is also the second point in solving the shortcomings.
Because in reading the official documentation I saw If string is not a string, then it is converted to one. This passage. That is to say, if the parameter is not a string, it will first convert it into a string and then into an integer. For example, parseInt(070) in Example (6) actually converts 070 into a string first. You can try 070+"" or String(070) and you can know that 070 will be converted to "56" because 070 is an octal system. Then it becomes parseInt("56"), and the final integer is 56. Whether you are in ES3 or ES5, it is 56
2. Bit operator
1. Example
console.log(0 | "123.45")//123console.log(0 | 123.45)//123console.log(0 ^ 123.45)//123console.log(~~123.45)//123
2. Principle: JavaScript does not have the concept of integers, and all numerical types are double-precision floating-point numbers. When using bit operators, it will first convert operands into integers for easy operation. 0 and other values will not change the operation value
3. Math.floor and Math.ceil
1. Example
console.log(Math.floor(2.3)//2console.log(Math.floor(-2.3)//-3console.log(Math.ceil(2.3)//3console.log(Math.ceil(-2.3)//-2
2. The two are insufficient: Math.floor gets the minimum integer of the number; while Math.ceil gets the maximum integer. So, if we rounded -2.3, we would get -2, but if we use Math.floor, we would get -3. 2.3 uses Math.ceil to get 3, but we just need 2.
3. Solve:
//Define a function function by yourself getInt(val){return val>0? Math.floor(val):Math.ceil(val);}