If you have a decimal that needs to be converted to an integer, you might think of parseInt():

parseInt(1.655)
/ / 1Copy the code

However, if so:

parseInt(0.00000060)
/ / 6Copy the code

It’s not what we thought it would be…

If you type 0.000000006 in DevTools, 6E-9 is returned. When you have consecutive zeros, it prints scientific notation like this.

So we have to hurry to MDN to see the interpretation of parseInt

The parseInt() function parses a string argument and returns an integer with a specified cardinality (the basis of a mathematical system). The parseInt function converts its first argument to a string, parses it, and returns an integer or NaN. If it is not a NaN, the value returned will be an integer as the first argument to the number in the specified radix (radix).

Going back to the example above, we typed 0.000000006, which first turned it into 6E-9, and then converted it to a string, but we encountered a non-numeric E, which stopped converting there even though it had a value of 2.718, and returned a value of 6

Now let’s enter the string 0.000000006 and it will return the correct result:

parseInt('0.000000006')
/ / 0Copy the code

As you can see, the parseInt method is not particularly safe. It does not return the correct result in some way. One solution is to place the number to be converted between double quotes.

However, this method is not so good. If we encounter such problems, we can try the following method

Method 1

Math methods can be used to round or truncate numbers, for example: math.round, math.ceil, math.floor, and math.trunc

Math.trunc is truncated from the decimal point and does not use any rounding.

Math.trunc(1.655)  
/ / 1Copy the code
Math.trunc(0.000000006)  
/ / 0Copy the code

For browsers that cannot use ES6, you can also use the following polyfill:

function ToInteger(v) {  
    if (v > 0) {
        return Math.floor(v);
    }
    return Math.ceil(v);
}

ToInteger(0.000000006) 
/ / 0Copy the code

Method 2

The faster way to convert integers is to use bitwise operations. Bitwise operations in JavaScript convert operands to 32-bit signed numbers and then perform bitwise operations on them.

We can use or to operate:

1.655 | 0
/ / 1Copy the code

1.655 converts to 0b00000001, and then performs or with 0. If there is a 1, then the result is 1. If both are 0, then the result is 0:

00000001  
   |
00000000  
-> 00000001Copy the code

And then we get one, and that’s what we want.

The disadvantage of this method is that it has a requirement for the input number, and can only be used for 32-bit binary representation.

If we try to convert 4000000000000000000000.1,

4000000000000000000000.1 | 0  
/ / 2055208960Copy the code

Method 1 does not have this problem, however, so if there are no large numbers (more than +/-2^32), bitwise is recommended, otherwise math.trunc is used

The resources

MDN parseInt

use-parseint-for-strings-not-for-numbers


Please subscribe to nuggets and Zhihu