Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C: Divide two integers and return a rounded integer value

How can I divide two NSIntegers, for instance, 13 / 4 and round the result to the next integer = 3?

I have seen some samples converting the integers to float and back to integer. But what is the recommended way with the least amount of code to do it?

like image 408
AlexR Avatar asked Dec 06 '22 11:12

AlexR


1 Answers

Assuming x >= 0 and y > 0:

If you want to round down: x / y

If you want to round up: (x + y - 1) / y

If you want to round to nearest: (x + y / 2) / y

like image 114
rob mayoff Avatar answered Jan 01 '23 06:01

rob mayoff