Skip to content

Conversation

@vrobinson-luna
Copy link
Contributor

Implements Integer.ceil_div, which complements Integer.floor_div by rounding towards positive infinity when the quotient would not be an integer.

Rationale for this function

Ceiling division is quite useful for chunking up data. For instance, if you want to split data into chunks of 1024, then Integer.ceil_div(data_size, 1024) will tell you the number of chunks that will result. Or, if you want to split a list into no more than eight chunks of similar size, you can do Integer.ceil_div(length(list), 8) to get such a chunk size.

As further justification, both of these chunking use-cases happen to be present in an Elixir codebase I work in. They're currently implemented as ceil(a / b), but a pure integer version of this operation (keeping it immune to any floating-point weirdness) would be more apropos in my opinion.

As a last point, it seems enough people have asked about this in other languages to make it seem a widely useful feature beyond the situations I myself have experienced.

So if the rationale seems convincing enough for this to be in the standard library, here's a PR :)

I also expanded the unit tests for Integer.floor_div and Integer.mod to cover a few more cases with different operand signs.

Copy link
Contributor

@sabiwara sabiwara left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The provided rationale makes sense to me, and I found occurrences of ceil(x/y) in my existing codebase at work too.
+1 for me!

end

test "mod/2" do
assert Integer.mod(10, -5) == 0
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(nit) the ordering of this case feels weird, would keep it after the positive args

@josevalim josevalim merged commit 51e25fb into elixir-lang:main Nov 15, 2025
13 checks passed
@josevalim
Copy link
Member

💚 💙 💜 💛 ❤️

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

3 participants