JavaScript Top Ten Rounding Method Example Tutorial

  • 2021-10-11 17:37:21
  • OfStack

1. parseInt()


// js Built-in function, note that the accepted parameters are string So there is a type conversion when the method is called 
parseInt("1.5555") // => 1

2. Number.toFixed(0)


//  Attention toFixed The returned string, if you want to get an integer, you need to do type conversion 
1.5555.toFixed(0) // => "1"

3. Math.ceil()


//  Rounding up 
Math.ceil(1.5555) // => 2

4. Math.floor()


//  Rounding down 
Math.floor(1.5555) // => 1

5. Math.round()


// 4 Shed 5 Input rounding 
Math.round(1.5555) // => 2

Math.round(1.4999) // => 1

6. Math.trunc()


//  Discard decimal rounding 
Math.trunc(1.5555) // => 1

7. Double bitwise non-rounding


//  Rounding by bit operation, only supports 32 Sign integer, decimal places will be discarded, the same below 
~~1.5555 // => 1

8. Bitwise or rounded


1.5555 | 0 // => 1

9. Bitwise XOR rounding


1.5555^0 // => 1

10. Left shift 0 bit rounding


1.5555<<0 // => 1

Among the 10 rounding methods mentioned above, the most commonly used estimates are the first two [I'm freaking out ~ ~], but from the performance point of view, bit rounding and Math function have the best performance, followed by built-in method parseInt and toFixed.

Here are the test results of Benchmark, which proves this point. toFixed performance is the worst:


//  Attention toFixed The returned string, if you want to get an integer, you need to do type conversion 
1.5555.toFixed(0) // => "1"
0

Benchmark source code

Reference

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

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

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


Related articles: