10

I have the following code:

int total = 6;
int perPage = 5;
double pages = total/perPage;
double ceilPages = Math.ceil(pages);
out.println(ceilPages);

Which outputs 1.0.

I thought it should output 2.0 because the result of total/perPage is 1.2.

Why is it not rounding upwards to 2.0?

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
crmepham
  • 4,676
  • 19
  • 80
  • 155
  • 7
    You are performing an integer division not a floating point one. – Sirko Jun 05 '14 at 14:10
  • 1
    `int ceilPages = (total + perPage - 1) / perPage;` is neater. – Joop Eggen Jun 05 '14 at 14:13
  • 1
    Did you try printing `pages` to see what value you passed into `Math.ceil()`? That would have immediately told you the problem was not with `Math.ceil()`. – dimo414 Jun 05 '14 at 14:41
  • possible duplicate of [How to Round Up The Result Of Integer Division](http://stackoverflow.com/questions/17944/how-to-round-up-the-result-of-integer-division) – Ali Jun 05 '14 at 14:42
  • (int)Math.ceil(3/2.0) will give answer 2 (int)Math.ceil(3/2) will give answer 1 In order to get the float value, you need to cast (or add .0) to one of the arguments – Shyam Sunder Mar 08 '18 at 16:34

3 Answers3

26

you are casting an the result of integer division to a double.

You need to cast each part of the division to double BEFORE the result.

double pages = (double)total/(double)perPage;

The rest should work

Adam Yost
  • 3,616
  • 23
  • 36
3

(int)Math.ceil(3/2.0) will give answer 2

(int)Math.ceil(3/2) will give answer 1

In order to get the float value, you need to cast (or add .0) to one of the arguments

Shyam Sunder
  • 523
  • 4
  • 13
0

double pages = Math.ceil((double)total/perPage);

Chandan Kumar
  • 99
  • 1
  • 8