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

Popular posts from this blog

oracle - The fastest way to check if some records in a database table? -

php - multilevel menu with multilevel array -

jQuery UI: Datepicker month format -