crmepham
crmepham

Reputation: 4740

Why is Math.ceil not rounding upwards?

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?

Upvotes: 10

Views: 13595

Answers (3)

Shyam Sunder
Shyam Sunder

Reputation: 703

(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

Upvotes: 3

Chandan Kumar
Chandan Kumar

Reputation: 109

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

Upvotes: 0

Adam Yost
Adam Yost

Reputation: 3625

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

Upvotes: 26

Related Questions