RunLoop
RunLoop

Reputation: 20376

Float comparison

I am embarrassed to ask this, but I am running iOS 6.1 and the following line returns False:

if ([[UIDevice currentDevice].systemVersion floatValue] >= 6.1)

yet the following returns True:

if ([[UIDevice currentDevice].systemVersion floatValue] >= 6.1f)

Why?

Upvotes: 4

Views: 2166

Answers (3)

RunLoop
RunLoop

Reputation: 20376

After quite a bit of reading, my understanding of the reason for this is as follows:

• C treats numbers like 1.2 as double and if modified with f e.g. 1.2f as a float • Neither doubles nor floats can be internally represented by the system with 100% accuracy • The representation errors for floats are higher than those for doubles

Therefor comparing a float to a double will mostly lead to misleading results. For non-critical systems, comparing 2 floats is sufficient.

Upvotes: 0

pdrcabrod
pdrcabrod

Reputation: 1477

In the first one systemVersion is converted from float to double and its value depends on how many bits you use to represent it

In the second one you are comparing two floats

Upvotes: 1

William Falcon
William Falcon

Reputation: 9813

Floats are cast to doubles before comparing. The f signals the number of decimals. You are comparing two different numbers when you change the number of decimals

Upvotes: 1

Related Questions