欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

JavaScript十大取整方法实例教程

程序员文章站 2022-09-29 21:36:17
1. parseint()// js内置函数,注意接受参数是string,所以调用该方法时存在类型转换parseint("1.5555") // => 12. number.tofixed(0)...

1. parseint()

// js内置函数,注意接受参数是string,所以调用该方法时存在类型转换
parseint("1.5555") // => 1

2. number.tofixed(0)

// 注意tofixed返回的字符串,若想获得整数还需要做类型转换
1.5555.tofixed(0) // => "1"

3. math.ceil()

// 向上取整
math.ceil(1.5555) // => 2

4. math.floor()

// 向下取整
math.floor(1.5555) // => 1

5. math.round()

// 四舍五入取整
math.round(1.5555) // => 2

math.round(1.4999) // => 1

6. math.trunc()

// 舍弃小数取整
math.trunc(1.5555) // => 1

7. 双按位非取整

// 利用位运算取整,仅支持32位有符号整型数,小数位会舍弃,下同
~~1.5555 // => 1

8. 按位运或取整

1.5555 | 0 // => 1

9. 按位异或取整

1.5555^0 // => 1

10. 左移0位取整

1.5555<<0 // => 1

上述10种取整方法中,最常用的估计是前2种 [我裂开了~~],不过从性能角度看,位运算取整和math函数性能最佳,内置方法parseint次之,tofixed性能最劣。

以下是benchmark测试结果,证明了这点,tofixed性能是最差的:

darwin x64
整数取整#getnum1#parseint x 210,252,532 ops/sec ±2.74% (85 runs sampled)
整数取整#getnum2#tofixed x 3,281,188 ops/sec ±1.54% (86 runs sampled)
整数取整#getnum3#math.ceil x 778,272,700 ops/sec ±3.97% (87 runs sampled)
整数取整#getnum4#math.floor x 816,990,140 ops/sec ±0.54% (88 runs sampled)
整数取整#getnum5#math.round x 814,868,414 ops/sec ±0.65% (88 runs sampled)
整数取整#getnum6#math.trunc x 821,032,596 ops/sec ±0.54% (91 runs sampled)
整数取整#getnum7#~~num x 813,589,741 ops/sec ±0.67% (90 runs sampled)
整数取整#getnum8#num | 0 x 815,070,107 ops/sec ±0.65% (90 runs sampled)
整数取整#getnum9#num ^ 0 x 812,635,464 ops/sec ±0.74% (90 runs sampled)
整数取整#getnum10#num << 0 x 819,230,753 ops/sec ±0.49% (91 runs sampled)
fastest is 整数取整#getnum6#math.trunc,整数取整#getnum10#num << 0

benchmark源代码

参考

developer.mozilla.org/zh-cn/docs/

developer.mozilla.org/zh-cn/docs/

developer.mozilla.org/zh-cn/docs/

到此这篇关于javascript十大取整方法的文章就介绍到这了,更多相关js取整方法内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

相关标签: js 取整