2

I am dividing two ints x/y,. Say 3/2. Then one would get 1 as result though the actual result is 1.5. Ok this is obvious as it's int division. But I want 1.5 to be rounded off to the next highest int not the immediate lowest. So 2 is desired as result. (One can write simple logic using mod and then division... But am looking for simple Java based API). Any thoughts?

samshers
  • 1
  • 6
  • 37
  • 84

4 Answers4

4

You can, in general, write (x + y - 1) / y to get the rounded-up version of x/y. If it's 3/2, then that becomes (3 + 2 - 1) / 2 = 4 / 2 = 2.

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
2

You can use the ceil (ceiling) function: https://docs.oracle.com/javase/7/docs/api/java/lang/Math.html#ceil(double)

That will essentially round up to the nearest whole number.

Russell
  • 17,481
  • 23
  • 81
  • 125
0

If you can change the datatype to double, following is the best solution -

double x = 3;
double y = 2;        
Math.ceil(Math.abs(x/y));

This will give you 2.0

Rishikesh Dhokare
  • 3,559
  • 23
  • 34
0
import java.lang.Math;
//round Up   Math.ceil(double num)
//round Down Math.floor(double num)
public class RoundOff 
{
 public static void main(String args[])
 { //since ceil() method takes double datatype value as an argument
   //either declare at least one of this variable as double
    int x=3; 
    int y=2; //double y =2;

   //or at least cast one of this variable as a (double) before taking division
    System.out.print(Math.ceil((double)x/y)); //prints 2.0
   //System.out.print(Math.ceil(x/y));
 }
}
Tanmay jain
  • 814
  • 6
  • 11
  • Code-only answers are very seldom helpful. Please explain how your code answers the question. For us all to learn. Thank you. – Ole V.V. Jan 18 '18 at 07:45
  • thanks for suggestion I thought code is simple enough to be understood directly by looking at it ,as I have already shown the important thing through the comment. – Tanmay jain Jan 19 '18 at 12:10