Monday, June 3, 2024
66
rated 0 times [  72] [ 6]  / answers: 1 / hits: 33727  / 15 Years ago, sun, january 24, 2010, 12:00:00

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;
 }

More From » bit-manipulation

 Answers
52

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;

[#97764] Tuesday, January 19, 2010, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tonisandyp

Total Points: 694
Total Questions: 97
Total Answers: 77

Location: British Indian Ocean Territory
Member since Tue, Feb 22, 2022
2 Years ago
;