SoFunction
Updated on 2025-04-03

The top ten rounding methods tutorials for JavaScript

1. parseInt()

// js built-in function, note that accepting parameters is string, so there is a type conversion when calling this methodparseInt("1.5555") // => 1

2. (0)

// Pay attention to the string returned by toFixed. If you want to obtain integers, you still need to do type conversion.1.(0) // => "1"

3. ()

// Round up(1.5555) // => 2

4. ()

// Round down(1.5555) // => 1

5. ()

// Rounding(1.5555) // => 2

(1.4999) // => 1

6. ()

// Abandon decimals to round(1.5555) // => 1

7. Double bitwise non-rounding

// Use bit operation to round, only 32-bit signed integer numbers are supported, and the decimal places will be discarded, the same below~~1.5555 // => 1

8. Rotate or round

1.5555 | 0 // => 1

9. Bitwise XOR rounding

1.5555^0 // => 1

10. Turn left by 0 bits

1.5555<<0 // => 1

Among the 10 rounding methods mentioned above, the most commonly used estimates are the first two [I split ~~]. However, from a performance perspective, bit operation rounding and Math function perform the best, with the built-in method parseInt second, and toFixed the worst performance.

Here are the results of Benchmark tests, which prove that toFixed has the worst performance:

darwin x64
Integer rounding#getNum1#parseInt x 210,252,532 ops/sec ±2.74% (85 runs sampled)
Integer rounding#getNum2#toFixed x 3,281,188 ops/sec ±1.54% (86 runs sampled)
Integer rounding#getNum3# x 778,272,700 ops/sec ±3.97% (87 runs sampled)
Integer rounding#getNum4# x 816,990,140 ops/sec ±0.54% (88 runs sampled)
Integer rounding#getNum5# x 814,868,414 ops/sec ±0.65% (88 runs sampled)
Integer rounding#getNum6# x 821,032,596 ops/sec ±0.54% (91 runs sampled)
Integer rounding#getNum7#~~num x 813,589,741 ops/sec ±0.67% (90 runs sampled)
Integer rounding#getNum8#num | 0 x 815,070,107 ops/sec ±0.65% (90 runs sampled)
Integer rounding#getNum9#num ^ 0 x 812,635,464 ops/sec ±0.74% (90 runs sampled)
Integer rounding#getNum10#num &lt;&lt; 0 x 819,230,753 ops/sec ±0.49% (91 runs sampled)
Fastest is Integer rounding#getNum6#, round the integer#getNum10#num << 0

Benchmarksource code

refer to

/zh-CN/docs/

/zh-CN/docs/

/zh-CN/docs/

This is the end of this article about the top ten rounding methods of JavaScript. For more related JS rounding methods, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!