Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript trunc() function

Tags:

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;
 }
like image 978
Dan Avatar asked Jan 24 '10 02:01

Dan


People also ask

What is the difference between math trunc () and Math floor () in JavaScript?

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.

What does the trunc number function do?

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.

What is the difference between floor and trunc?

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.

How do you round down in JavaScript?

The Math. floor() method rounds a number DOWN to the nearest integer.


2 Answers

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;
like image 108
Christian C. Salvadó Avatar answered Sep 28 '22 22:09

Christian C. Salvadó


For positive numbers:

Math.floor(2.6) == 2;

For negative numbers:

Math.ceil(-2.6) == -2;
like image 24
Daniel Vassallo Avatar answered Sep 28 '22 22:09

Daniel Vassallo