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

Watch out for floating-point error

This lesson covers floating-point error in Objective-C, with the aim of understanding why decimal arithmetic can give surprising results.

Computers hold decimals in binary, so even a simple calculation such as 0.1 + 0.2 may not come out exactly 0.3. Displayed, the error shows; compared, you get false.

The sample code displays the value carrying an error with the high-precision specifier NSLog(@"%.17g", a) and shows that the comparison a == 0.3 comes back false. This happens in most languages that use floating point.

A common early stumble is comparing decimals directly with == and not getting the expected result. Knowing that the behaviour follows the IEEE 754 standard makes the cause much clearer.

In professional work, calculations that must be exact — money, for instance — are better handled with a higher-precision type such as NSDecimalNumber.

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