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

Formatting numbers (aligning digits and decimal places)

This lesson covers formatting numbers in Objective-C, with the aim of displaying them in a readable form.

NSLog(@"%.2f", value) fixes the number of decimal places and NSLog(@"%03ld", value) pads the front with zeros to a fixed width. Both are handy for displaying amounts and for building numbered file names. C's format specifiers work as they are.

The sample code turns 1234.5 into two-decimal form with NSLog(@"%.2f dollars", price) and 7 into the zero-padded "007" with NSLog(@"%03ld", (long)num).

A common early stumble is the cast needed when formatting an NSInteger. Its internal representation varies by platform, so casting to (long) and using %ld is the safe practice.

In professional work, results displayed raw have inconsistent widths and read badly, so this kind of formatting just before display is standard.

๐Ÿ“– 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)