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

Answer from Adam Yost on Stack Overflow
Top answer
1 of 3
28

This is probably because when you divide an Integer by an Integer you get an Integer back which has the same value as Decimal.round(RoundingMode.DOWN).

system.assertEquals(1, 8/5);
system.assertEquals(8/5, (8.0/5).round(RoundingMode.DOWN);

system.assertEquals(-1, -8/5);
system.assertEquals(-8/5, (-8.0/5).round(RoundingMode.DOWN);

system.assertEquals(2, 7/3);
system.assertEquals(7/3, (7.0/3).round(RoundingMode.DOWN);

If you know you have Integers and you want to get their ceiling, you could do something like:

public static Integer ceiling(Integer x, Integer y)
{
    return Math.ceil(Decimal.valueOf(x).divide(y, /*digits*/ 1));
}
2 of 3
17

Integer Division

In Apex Code, similar to Java, when there are two like numeric data types (e.g. both Integers), then they are calculated in a way that returns the same data type. Integers cannot store fractions, so when you do something like 7/3, the fraction is silently discarded. As far as I know, integer division works in the same for every programming language in the world where the result of integer arithmetic is an integer.In many languages where the result of two integers being divided together results in an integer, the fraction is often dropped entirely, although exceptions do exist (some perform rounding, instead).

Parameter Promotion

You'll notice that there's no function Math.ceil that accepts an Integer. This means if you give it an integer, it will implicitly be cast to a floating point value before being processed by Math.ceil.

Arithmetic Promotion

When two numbers are operated on using the standard operators (+, -, /, *), if one of those parameters are a floating point value, the other one will also automatically become a floating point value. Similarly, if a integer and a long were involved in an operation, both numbers become long, and the return type becomes long. So, the goal is to create a situation where a floating point is returned. For example, this results in the correct result:

Integer x = Math.ceil(7.0/3).intValue();

Here, the 7.0 indicates a floating point operation. You'd also get the same effect if you did this:

Decimal x = 7;
Integer y = 3;
Integer z = Math.ceil(x/y).intValue();

This behavior is well-defined, and mimics the behavior in Java. You can read more about automatic widening conversion in the Java documentation, as well as rules about integer division. You'll find that, while not explicitly mentioned in the Apex Code Developer's Guide (as far as I can tell), it obeys the same rules.

Top answer
1 of 15
246

You are doing 157/32 which is dividing two integers with each other, which always result in a rounded down integer. Therefore the (int) Math.ceil(...) isn't doing anything. There are three possible solutions to achieve what you want. I recommend using either option 1 or option 2. Please do NOT use option 0.

Option 0

Convert a and b to a double, and you can use the division and Math.ceil as you wanted it to work. However I strongly discourage the use of this approach, because double division can be imprecise. To read more about imprecision of doubles see this question.

int n = (int) Math.ceil((double) a / b));

Option 1

int n = a / b + ((a % b == 0) ? 0 : 1); 

You do a / b with always floor if a and b are both integers. Then you have an inline if-statement which checks whether or not you should ceil instead of floor. So +1 or +0, if there is a remainder with the division you need +1. a % b == 0 checks for the remainder.

Option 2

This option is very short, but maybe for some less intuitive. I think this less intuitive approach would be faster than the double division and comparison approach:
Please note that this doesn't work for b < 0.

int n = (a + b - 1) / b;

To reduce the chance of overflow you could use the following. However please note that it doesn't work for a = 0 and b < 1.

int n = (a - 1) / b + 1;

Explanation behind the "less intuitive approach"

Since dividing two integers in Java (and most other programming languages) will always floor the result. So:

int a, b;
int result = a/b (is the same as floor(a/b) )

But we don't want floor(a/b), but ceil(a/b), and using the definitions and plots from Wikipedia:

With these plots of the floor and ceil functions, you can see the relationship.

You can see that floor(x) <= ceil(x). We need floor(x + s) = ceil(x). So we need to find s. If we take 1/2 <= s < 1 it will be just right (try some numbers and you will see it does, I find it hard myself to prove this). And 1/2 <= (b-1) / b < 1, so

ceil(a/b) = floor(a/b + s)
          = floor(a/b + (b-1)/b)
          = floor( (a+b-1)/b) )

This is not a real proof, but I hope you're satisfied with it. If someone can explain it better I would appreciate it too. Maybe ask it on MathOverflow.

2 of 15
62

157/32 is int/int, which results in an int.

Try using the double literal - 157/32d, which is int/double, which results in a double.

🌐
Tutorialspoint
tutorialspoint.com › java › lang › math_ceil.htm
Java - Math ceil(double) Method
package com.tutorialspoint; public class MathDemo { public static void main(String[] args) { // get a double number double x = 10.7; // print the ceil of the number System.out.println("Math.ceil(" + x + ")=" + Math.ceil(x)); } }
🌐
Programiz
programiz.com › java-programming › library › math › ceil
Java Math ceil()
Here, ceil() is a static method. Hence, we are accessing the method using the class name, Math. The ceil() method takes a single parameter. ... Note: The returned value will be the smallest value that is greater than or equal to the specified argument.
🌐
W3Schools
w3schools.com › java › ref_math_ceil.asp
Java Math ceil() Method
Java Examples Java Videos Java Compiler Java Exercises Java Quiz Java Code Challenges Java Server Java Syllabus Java Study Plan Java Interview Q&A Java Certificate ... System.out.println(Math.ceil(0.60)); System.out.println(Math.ceil(0.40)); System.out.println(Math.ceil(5)); System.out.println(Math.ceil(5.1)); System.out.println(Math.ceil(-5.1)); System.out.println(Math.ceil(-5.9));
Find elsewhere
🌐
Scaler
scaler.com › home › topics › math.ceil() in java
Math.ceil() in Java - Scaler Topics
May 5, 2024 - Explanation: The value of 5/3 will be 1.6666667, and when we typecast this to int, it will become 1. However, if we use Math.ceil() before typecasting Math.ceil(), it will convert 1.666667 to 2.0, and then 2.0 is typecasted to 2. If the input parameter is a character, the ceil() function will return the ceil of the ASCII value of that character, which will be the ASCII value. Note: A compile-time error will be thrown if String is passed as a parameter.
🌐
Javatpoint
javatpoint.com › java-math-ceil-method
Java Math.ceil() method with Examples - Javatpoint
Java CopyOnWriteArrayList · indexOf() lastIndexOf() clone() toArray() Math.abs() Math.max() Math.min() Math.round() Math.sqrt() Math.cbrt() Math.pow() Math.signum() Math.ceil() Math.copySign() Math.nextAfter() Math.nextUp() Math.nextDown() Math.floor() Math.floorDiv() Math.random() Math.rint() Math.hypot() Math.ulp() Math.getExponent() Math.IEEEremainder() Math.addExact() Math.subtractExact() Math.multiplyExact() Math.incrementExact() Math.decrementExact() Math.negateExact() Math.toIntExact() Math.log() Math.log10() Math.log1p() Math.exp() Math.expm1() Math.sin() Math.cos() Math.tan() Math.asin() Math.acos() Math.atan() Math.sinh() Math.cosh() Math.tanh() Math.toDegrees ·
🌐
Coderanch
coderanch.com › t › 548975 › java › Java-Math-Floor-Ceil-returning
Java Math - Floor/Ceil returning double (Java in General forum at Coderanch)
I was looking through the Java source, and apparently values too large are ignored: In short, the argument that ceil/floor return double 'because the input may be outside the range of long' is flawed because in actuality you should never call ceil/floor on those values anyway.
🌐
Sololearn
sololearn.com › en › Discuss › 2411707 › why-is-mathceil-function-malfunctioning-in-code-coach-section
Why is Math.ceil function malfunctioning in code coach section... | Sololearn: Learn to code for FREE!
xᴏᴊɪᴀᴋʙᴀʀ in Java it's Math.floor for nearest small... Math.ceil for nearest big number ... Thanks Jayakrishna🇮🇳 ... Math.ceil requires double parameters ... Aaron 5/2 result 2 because both integers.
🌐
CodeGym
codegym.cc › java blog › java math › java math.ceil() method
Java Math.ceil() method
October 11, 2023 - “A ceil function converts a decimal ... then the same number is the ceiling value. However, if you pass a null value to the ceil function in mathematics you get a “zero”. Java provides a built-in method to compute the ceil function ...
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-ceil-method-examples
Java ceil() method with Examples - GeeksforGeeks
April 7, 2018 - The Math class is used to access the ceil() method. Variable a holds a positive decimal value, which is rounded up to the next integer. Variable b represents positive infinity, so the result remains infinity. Variable c is positive zero, and the output remains 0.0. Variable d is negative zero, and the output remains -0.0. Variable e is a negative value between -1.0 and 0.0, so the result is -0.0. Each result is printed to show how Math.ceil() behaves in different cases.
🌐
Guru99
guru99.com › home › java tutorials › java math – ceil() floor() methods
Java Math – ceil() Floor() Methods
September 20, 2024 - Hence the Math class java provides these two constants as double fields. ... Note: There is no need to explicitly import java.lang.Math as its imported implicitly.
🌐
Tutorial Gateway
tutorialgateway.org › java-ceil-function
Java ceil Function
March 25, 2025 - If the number argument is a positive or negative number, the Java Math ceil function will return the ceiling value. If the number argument is positive or negative zero, it will return the same argument. It will return the same argument when the number argument is not a number (NaN) or Infinity.
🌐
BeginnersBook
beginnersbook.com › 2022 › 10 › java-math-ceil-method
Java Math.ceil() Method
public class JavaExample { public static void main(String[] args) { double n = 0.0/0; //NaN System.out.println("Ceil for NaN: "+Math.ceil(n)); } } Output: Java Math.signum() Java Math.pow() Java Math.cbrt() Java Math.sqrt() ❮ Java Math · Java StringBuffer setLength() Method · Java Math.random() Method · Java Math.exp() Method · Java null literal · Java Math.cos() Method · I have 15 years of experience in the IT industry, working with renowned multinational corporations.