0

before asking question I would like to let you all know that I did see some similar questions from past posts but when applied, won't quite work as intended... So basically, I want to ceil round an integer to a multiple of 60. As an example, if a number that I want to ceil round is 160 to a multiple of 60, the result should yield 180; (because out of 60->120->180; 160 is closest to 180 than 120); my test code looks like this:

public static void main (String[] args) {
  double a = Math.ceil(160/60)*60;
  System.out.println(a);
}

and the output that it gives is 120.0; instead of 180.

What exactly is wrong with the test code for it to yield 120 rather than 180? Am I using the ceil() wrongly?

J.J.Trie
  • 13
  • 1
  • 3

2 Answers2

1

You are using integer division which will result in an integer. So as others pointed out : 160/60 returns 2, not 2,66 that you expect to round up to 3.

public static void main (String[] args) {
  double a = Math.ceil((float)160/60)*60;
  System.out.println(a);
}
Tadija Bagarić
  • 2,495
  • 2
  • 31
  • 48
0

Since your input is an integer and your output is an integer too, it would be cleaner to implement your own ceiling function:

int ceil(int num, int mod) {
  int remainder = num % mod;
  if (remainder < mod / 2) {
    return num - remainder;
  }
  return num - remainder + mod;
}

For example, this will give:

  • 180 for (160, 60) and (150, 60)
  • 120 for (149, 60)
janos
  • 120,954
  • 29
  • 226
  • 236
  • But this isn't a ceiling function. The ceiling of _x_ is the least integer that's greater than or equal to _x_. – Dawood ibn Kareem Jul 22 '17 at 08:33
  • @DawoodibnKareem that's a narrow way of thinking of ceiling. What you say is the traditional definition of ceiling of floating point numbers with respect to integer boundaries. You can easily generalize and extend that concept to larger intervals than 1. It's a useful abstraction to solve the main question at hand. – janos Jul 22 '17 at 08:39