There are many ways to convert a floating point number to an integer. In this example, we will introduce three common methods. If you think of other useful methods, you can also share them.
Summary
For now, I just thought of three methods. If you think of other useful methods, You can also talk about them.
ParseInt
Bitwise operators
Math. floor Math. ceil
Description
I. parseInt
1. Instance
ParseInt ("13 nash"); // 13 parseInt ("") // NaNparseInt ("0xA") // 10 (hexadecimal) parseInt ("13 ") // 13 parseInt ("070") // ES3 is 56 (octal) ES5 is 70 parseInt (070) // ES3 and ES5 are both 56 parseInt (22.5) // 22
2. conversion rules:
(1). According to instance (1), the parseInt will be parsed until it is not a number.
(2). According to instance (2), the parseInt parses the Null String as NaN, instead of 0.
(3) According to instance (3), the parseInt can be used to convert the hexadecimal number to the hexadecimal number.
(4). Based on instance (4), get parseInt to ignore the space of the string
3. Disadvantages:
(1). According to instance (5), we can know that parseInt is incompatible when converting the octal array. ES3 regards 070 as an octal value, but ES5 regards 070 as decimal.
(2). Based on instance (6) (7), we can know that parseInt will first convert the parameter into a string before being executed into an integer.
4. Explanation: (5) (6) Why do the execution tasks convert 070 to an integer, but the results are different? This is also the second point to solve the problem.
In the official document, I see If string is not a string, then it is converted to one. This section. That is to say, if the parameter is not a string, it will first convert it into a string and then convert it into an integer. For example, in instance (6), parseInt (070) converts 070 to a String. You can try 070 + "or String (070) you can know that 070 will be converted to "56", because 070 is an octal. Then it becomes parseInt ("56"), and the final integer is 56. Whether you are in ES3 or ES5, It is 56.
Ii. bitwise operators
1. Instance
console.log(0 | "123.45")//123console.log(0 | 123.45)//123console.log(0 ^ 123.45)//123console.log(~~123.45)//123
2. Principle: javascript has no Integer Concept. All numeric types are double-precision floating-point numbers. When a bitwise operator is used, it first converts the operand into an integer to facilitate operations. 0 is different from other values or does not change the operation value by bit or
Math. floor and Math. ceil
1. Instance
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 not enough: Math. floor gets the smallest integer of the number, while Math. ceil gets the largest integer. So what we need to get is-2 if we get an integer from-2.3, but what we get from Math. floor is-3. In 2.3, Math. ceil is used to get 3, but we only need 2.
3. solution:
// Define a function getInt (val) {return val> 0? Math. floor (val): Math. ceil (val );}