-2

this may be a trivial question but I need to round a double away from zero - and I can't seem to find a method that does that easily - i know i could implement it myself but I'd only do that if it's absolutely necessary.

raphi011
  • 502
  • 1
  • 6
  • 23

2 Answers2

4

You can use a combination of Math.ceil and Math.floor:

(x > 0) ? Math.ceil(x) : Math.floor(x)

If x is positive, we "round up" using ceil; if x is negative (or zero) we "round down" using floor.

arshajii
  • 127,459
  • 24
  • 238
  • 287
0

In addition to the already suggested ceil and floor combination:

Math.ceil(Math.abs(x))*Math.signum(x);

It rounds up the absolute value, then puts the sign back by multiplying by Math.signum(x).

Patricia Shanahan
  • 25,849
  • 4
  • 38
  • 75