1. parseInt()

// javascript built-in function, note that it accepts a string argument, so there is a type conversion when calling this method
parseInt("1.5555") / / = > 1
Copy the code

2. Number.toFixed(0)

// Note the string returned by toFixed. If you want to get an integer, you need to do a type conversion
1.5555.toFixed(0)  / / = > "1"
Copy the code

3. Math.ceil()

// round up
Math.ceil(1.5555) / / = > 2
Copy the code

4. Math.floor()

// round down
Math.floor(1.5555) / / = > 1
Copy the code

5. Math.round()

// Round up
Math.round(1.5555) / / = > 2

Math.round(1.4999) / / = > 1
Copy the code

6. Math.trunc()

// Discard decimals and round them
Math.trunc(1.5555) / / = > 1
Copy the code

7. Double bitwise non-integer

// Only 32-bit signed integers are supported. The decimal place is discarded. The following is the same~ ~1.5555 / / = > 1
Copy the code

8. Carry or round by bit

1.5555 | 0  / / = > 1
Copy the code

9. Xor by bit

1.5555^0  / / = > 1
Copy the code

10. Move 0 bit to the left to round

1.5555<<0 / / = > 1
Copy the code

The most common estimates of the above 10 integer methods are the first two [I cracked ~ ~], but from a performance perspective, the bitwise integer and Math functions perform best, followed by the built-in methods parseInt and toFixed.

Here are the Benchmark results to prove this, and toFixed’s performance is the worst:

Darwin x64 integer integer integer #getNum1#parseInt x 210,252,532 ops/ SEC ±2.74% (85 runs sampled) integer #getNum2#toFixed x 3,281,188 ops/ SEC Ceil x 788,272,700 OPS/SEC ±3.97% (87 runs tos) integer 799 #getNum4# math.floor X 816990140 ops/SEC plus or minus 0.54% (88 runs the javax.media.sound.sampled) integer integer # # getNum5 math.h round x 814868414 ops/SEC plus or minus 0.65% (88 runs the javax.media.sound.sampled) Trunc x 821,032,596 OPS/SEC ±0.54% (91 runs sampled) The integer #getNum7#~~num x 813,589,741 OPS/SEC ±0.67% Integer (90 runs the javax.media.sound.sampled) integer # getNum8 # num | 0 x 815070107 ops/SEC plus or minus 0.65% (90 runs the javax.media.sound.sampled) integer integer # getNum9 # num ^ 0 x 812635464 Ops/SEC ±0.74% (90 runs sampled) Fastest is a integer integer (getNum10#num << 0 x 128, 300, 300) ops/ SEC ±0.49% (91 runs sampled) Fastest is Trunc #getNum10#num << 0Copy the code

Benchmark source code

More and more

In js, in addition to helping us to round integers, we can also reverse the use of its properties to determine whether a 32-bit signed integer overflows, which helps us to write more concise code, such as:

let result =  x << 0 === x ? x : 0;
// Return 0 if x > 2^ 31-1 or x < -2^31, the rest of the time x is unchanged.
Copy the code

reference

Developer.mozilla.org/zh-CN/docs/…

Developer.mozilla.org/zh-CN/docs/…

Developer.mozilla.org/zh-CN/docs/…