I want to truncate a number in javascript, that means to cut away the decimal part:
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;
}
Math. trunc rounds down a number to an integer towards 0 while Math. floor rounds down a number to an integer towards -Infinity . As illustrated with the following number line, the direction will be the same for a positive number while for a negative number, the directions will be the opposite.
TRUNC removes the fractional part of the number. INT rounds numbers down to the nearest integer based on the value of the fractional part of the number. INT and TRUNC are different only when using negative numbers: TRUNC(-4.3) returns -4, but INT(-4.3) returns -5 because -5 is the lower number.
Definition of floor R function: The floor function rounds a numeric input down to the next lower integer. Definition of trunc R function: The trunc function truncates (i.e. cuts off) the decimal places of a numeric input.
The Math. floor() method rounds a number DOWN to the nearest integer.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With