javascript trunc() function
I want to truncate a number in javascript, that means to cut away the decimal part开发者_StackOverflow社区:
trunc ( 2.6 ) == 2
trunc (-2.6 ) == -2
After heavy benchmarking my answer is:
function trunc (n) {
return ~~n;
}
// or
function trunc1 (n) {
return n | 0;
}
As an addition to the @Daniel's answer, if you want to truncate always towards zero, you can:
function truncate(n) {
return n | 0; // bitwise operators convert operands to 32-bit integers
}
Or:
function truncate(n) {
return Math[n > 0 ? "floor" : "ceil"](n);
}
Both will give you the right results for both, positive and negative numbers:
truncate(-3.25) == -3;
truncate(3.25) == 3;
For positive numbers:
Math.floor(2.6) == 2;
For negative numbers:
Math.ceil(-2.6) == -2;
You can use toFixed method that also allows to specify the number of decimal numbers you want to show:
var num1 = new Number(3.141592);
var num2 = num1.toFixed(); // 3
var num3 = num1.toFixed(2); // 3.14
var num4 = num1.toFixed(10); // 3.1415920000
Just note that toFixed rounds the number:
var num1 = new Number(3.641592);
var num2 = num1.toFixed(); // 4
I use
function trunc(n){
return n - n % 1;
}
because it works over the whole float range and should (not measured) be faster than
function trunc(n) {
return Math[n > 0 ? "floor" : "ceil"](n);
}
In case it wasn't available before and for anyone else who stumbles upon this thread, you can now simply use the trunc() function from the Math library, like so:
let x = -201;
x /= 10;
console.log(x);
console.log(Math.trunc(x));
>>> -20.1
>>> -20
精彩评论