tags:

views:

656

answers:

2

I want to truncate a number in javascript

trunc(2.6)==2
+2  A: 

For positive numbers:

Math.floor(2.6) == 2;

For negative numbers:

Math.ceil(-2.6) == -2;
Daniel Vassallo
+3  A: 

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