Math.floor VS Math.trunc JavaScript [英] Math.floor VS Math.trunc JavaScript

查看:175
本文介绍了Math.floor VS Math.trunc JavaScript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

背景



我正在创建一个接收正数的函数,然后将数字四舍五入到它下面最接近的整数。



我一直在使用


Background

I am making a function that receives a positive number and then rounds the number to the closest integer bellow it.

I have been using Math.floor, but recently I discovered Math.trunc.

I am aware that both will return the same value, given a positive number, and that they work in completely different ways. I am interested in exploring this behavior.

Questions

  1. Which one is faster ?
  2. Which one should I use?

解决方案

Actually, there is much more alternative ways to remove the decimals from a number. But it's a tradeoff of readability and speed.

Choosing the right one depends on what you need. If you just need to remove decimals, always use trunc() or bitwise operators.
floor(), ceil() and round() are conceptually very different from trunc().

Math library

You already know these. Always use them in a standard, non-critical code.

var v = 3.14;
[Math.trunc(v), Math.floor(v), Math.ceil(v), Math.round(v)]
// prints results

for different input values you get these results

          t   f   c   r
 3.87 : [ 3,  3,  4,  4]
 3.14 : [ 3,  3,  4,  3]
-3.14 : [-3, -4, -3, -3]
-3.87 : [-3, -4, -3, -4]


But this is more fun :)

Binary operations and bitwise operators

If you look at them in the code, it might not be apparent from the first glance what they do, so don't use them. Though in some cases, they might be useful. For example calculating coordinates in a <canvas/>. They are much faster, but come with limitations.

Conceptually, they work this way:

  • The operands are converted to 32-bit integers. (Numbers with more than 32 bits get their most significant bits discarded.)

Bitwise logical operators

  • Each bit in the first operand is paired with the corresponding bit in the second operand. (First bit to first bit, second bit to second bit, and so on.)
  • The operator is applied to each pair of bits, and the result is constructed bitwise.

Bitwise shift operators

  • These operators take a value to be shifted and a number of bit positions to shift the value by.

However, we always use a 0, zero, a false as a second operand, that doesn't do anything to the original value in these cases:

~    NOT    ~~v

|    OR    v | 0

<<   Left shift    v << 0

>>   Signed right shift    v >> 0

>>>  Zero-fill right shift    v >>> 0

var v = 3.78;
[ ~~v ,  v | 0 ,  v << 0 ,  v >> 0 ,  v >>> 0 ]
// prints these results

 3.78 : [ 3,  3,  3,  3, 3]
 3.14 : [ 3,  3,  3,  3, 3]
-3.74 : [-3, -3, -3, -3, 4294967293]
-3.14 : [-3, -3, -3, -3, 4294967293]


Performance

https://jsperf.com/number-truncating-methods/1

这篇关于Math.floor VS Math.trunc JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆