背景
我正在创建一个函数,它接收一个正数,然后将这个数字舍入到最接近的整数下面。
我一直在使用Math.floor,但最近我发现了Math.trunc。
我知道,如果数字为正数,两者将返回相同的值,而且它们的工作方式完全不同。我对探索这种行为感兴趣。
问题
发布于 2016-08-02 07:41:02
实际上,有更多的替代方法可以从一个数字中删除小数。但这是可读性和速度的权衡。
选择对的取决于你需要什么。如果您只需要删除小数,请始终使用trunc()或按位运算符。
floor()、ceil()和round()在概念上与trunc()有很大的不同。
数学库
你已经知道这些了。在标准的、非关键的代码中使用它们。
var v = 3.14; [Math.trunc(v), Math.round(v), Math.floor(v), Math.ceil(v)]
// prints results对于不同的输入值,您将得到以下结果
v t r f c
3.87 : [ 3, 4, 3, 4]
3.14 : [ 3, 3, 3, 4]
-3.14 : [-3, -3, -4, -3]
-3.87 : [-3, -4, -4, -3]Math.trunc() 删除(截断)小数位。
Math.round() 将转到最近的整数。
Math.floor() 将转到最接近的下整数。3.5 -> 3 -3.5 -> -4
Math.ceil() 将转到最接近的更高的整数。3.5 -> 4 -3.5 -> -3
但更有趣的是:)
二进制操作与位运算符
如果您在代码中查看它们,那么乍一看,它们所做的事情可能并不明显,所以不要在普通代码中使用它们。虽然在某些情况下,它们可能是有用的。例如,计算<canvas/>中的坐标。它们速度快得多,但也有局限性。
从概念上讲,它们的工作方式如下:
注意: 超过32位的数字得到最重要的(最左边)位弃置,而最左边的位成为新的符号位。 0b011100110111110100000000000000110000000000001,// 15872588537857 ~~0b011100110111110100000000000000110000000000001,// -1610588159 ~0b101000000000000001100000000001,// -1610588159
位逻辑运算符
位移位算子
value来移动,而一个位位置的number来移动value。截短
然而,在截断时,我们总是使用一个0,零,一个false作为第二个操作数,在这些情况下,除了转换为整数之外,它不会对原始值做任何事情:
~
|
<<-准准左移
>>准正向右移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]性能
https://jsperf.com/number-truncating-methods/1

发布于 2016-08-01 15:50:38
如果参数是正数,则Math.trunc()等价于Math.floor(),否则Math.trunc()则等价于Math.ceil()。
对于性能检查,这一项和最快的一项是Math.trunc。
var t0 = performance.now();
var result = Math.floor(3.5);
var t1 = performance.now();
console.log('Took', (t1 - t0).toFixed(4), 'milliseconds to generate:', result);
var t0 = performance.now();
var result = Math.trunc(3.5);
var t1 = performance.now();
console.log('Took', (t1 - t0).toFixed(4), 'milliseconds to generate:', result);结果是花费了0.0300毫秒来生成:3用了0.0200毫秒来生成:3
所以,如果参数只是正数,你可以使用最快的一个。
发布于 2021-03-16 17:23:17
现有的答案很好地解释了演出的情况。然而,我无法从问题或答案中理解Math.trunc和Math.floor之间的功能差异,因此我将我的发现放在了这个答案中。
Math.trunc将一个数字舍入一个整数到0,而Math.floor将一个数字舍入到一个整数到-Infinity。如下面的数字行所示,正数的方向相同,而负数的方向则相反。
trunc: towards 0
floor: towards -Infinity
-3 -2 -1 0 1 2 3
-Infinity ... ------+----|--+------+------+------+------+--|----+------ .... Infinity
b a 演示:
var a = 2.3, b = -2.3;
console.log("\t\t\t" + a + "\t\t" + b + "\r\n" + "Math.trunc: " + Math.trunc(a) + "\t\t" + Math.trunc(b) + "\r\n" + "Math.floor: " + Math.floor(a) + "\t\t" + Math.floor(b));输出:
2.3 -2.3
Math.trunc: 2 -2
Math.floor: 2 -3https://stackoverflow.com/questions/38702724
复制相似问题