Ad space (banner)
๐ŸŽObjective-C Lessons
Lesson 45 / 68

Rounding numbers (floor, ceil, round)

This lesson covers rounding decimals in Objective-C, with the aim of choosing the right method for the purpose.

floor() rounds down, ceil() rounds up, and round() rounds to nearest. Picture shaving down, bumping up, and snapping to whichever is closer. These come straight from C's math.h.

The sample code shows that similar-looking decimals give different results depending on the function: floor(3.7) is 3.0, ceil(3.2) is 4.0, and round(3.5) is 4.0. Note that all three return a double.

A common early stumble is that these are C functions and so read quite differently from Foundation's object-oriented style. C functions for primitive numbers, methods for objects — the split has to be kept in mind.

In professional work, the choice matters — rounding in a monetary calculation, aligning decimal places for display — because the result changes with it.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Objective-C directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)