bit manipulation - javascript trunc() function -
I want to minimize a number in JavaScript, which means to cut the decimal part:
Trunk (2.6) == 2
Trunk (-2.6) == -2
My answer after heavy benchmarking is:
function trunk (n) {return ~~ n; } // or function trunc1 (n) {return n | 0; }
In addition to the answer, if you want to minimize always, zero It can:
function threnetate (n) {return n | 0; // bitwise operators convert to 32-bit integer}
or:
function trunket (n) {return mathematics [n & gt; 0? "Floor": "roof"] (n); }
Both will give you the correct result for both positive and negative numbers:
truncate (-3.25) == -3; Fixing (3.25) == 3;
Comments
Post a Comment