Rust Rounding Division
Rounding division is division that chooses which way to round the result. div_ceil rounds a division up.
Plain division drops the part box
Ten items, three to a box. Plain / counts only the full boxes:
let items = 10u32;
let per_box = 3u32;
println!("full boxes = {}", items / per_box);div_ceil counts the part box too
The same numbers with div_ceil round the answer up, so the leftover items get a box:
let items = 10u32;
let per_box = 3u32;
println!("boxes needed = {}", items.div_ceil(per_box));An exact fit does not round up
Rounding up only happens when something is left over:
println!("{}", 12u32.div_ceil(3));
println!("{}", 10u32.div_ceil(5));Negative numbers round the other way
Signed types have no div_ceil yet. For negatives, plain / already rounds up, towards zero — and div_euclid rounds down instead:
println!("{}", -7 / 2);
println!("{}", (-7i32).div_euclid(2));The matching remainder: rem_euclid
The remainder has the same split. % keeps the sign of the left side, so it can be negative. rem_euclid is div_euclid's partner and stays positive:
println!("{}", (-7i32).rem_euclid(2));
println!("{}", (-7i32) % 2);Example
fn main() {
let photos = 137u32;
let per_page = 12u32;
println!("pages = {}", photos.div_ceil(per_page));
println!("full pages = {}", photos / per_page);
println!("photos on last page = {}", photos % per_page);
let start_temp = -7i32;
println!("-7 / 2 = {}", start_temp / 2);
println!("euclid = {} remainder {}", start_temp.div_euclid(2), start_temp.rem_euclid(2));
}Key points
- Use div_ceil on unsigned integers to round a division up: 10u32.div_ceil(3) is 4
- An exact fit does not round up: 12u32.div_ceil(3) is 4, not 5
- Plain / rounds towards zero: for negative numbers that means up — -7 / 2 is -3
- Use div_euclid and rem_euclid as a pair for signed values: (-7i32).div_euclid(2) is -4 and (-7i32).rem_euclid(2) is 1
- Signed integers do not have div_ceil yet.
- In the standard library it is still experimental.
- Unsigned types have had it since Rust 1.73
In this example, 137 photos go 12 to a page. div_ceil answers the practical question. The answer is 12 pages. The last 5 photos still need a page of their own. Plain / counts only the 11 full pages. % counts the 5 leftovers. The temperature lines show the signed split. -7 / 2 rounds towards zero. It gives -3. div_euclid rounds down to -4. rem_euclid keeps the remainder positive at 1. Check the pair: -4 × 2 + 1 = -7, so the euclid answers always add back up.
Note
Pages, boxes and trips are the classic div_ceil jobs: items.div_ceil(per_page) is exactly the number of pages.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Rust Playground
Exercise
Thirty people arrive, and each row seats 8. Which expression gives the number of rows needed?