19

When I run the following code ,

NSString* s= @"10000000.01"; float f = [s floatValue]; double d = [s doubleValue]; if(f > 10000000) { NSLog(@"Over Value"); } else { NSLog(@"OK Float"); } if(d > 10000000) { NSLog(@"Over value"); } else { NSLog(@"OK Double"); } 

The response is like following.

2013-04-19 17:07:29.284 float[2991:907] OK Float 2013-04-19 17:07:29.287 float[2991:907] Over value 

Why float value changed to 10000000.00 instead of 10000000.01 ?

1
  • 6
    SA is Google. The place where most people end up when googling ;) Commented May 30, 2017 at 22:15

3 Answers 3

44

float is 32-bit while double is 64-bit. A float has fewer significant digits than double.

A float value doesn't store enough to hold the 10 digits of your 10000000.01.

Also see Difference between float and double for more details. That is about C/C++ but it applies to Objective-C as well.

Sign up to request clarification or add additional context in comments.

Comments

3

Double

  1. Represents a 64-bit floating-point number.
  2. Has a precision of at least 15 decimal digits.

Float

  1. Float represents a 32-bit floating-point number.
  2. precision of Float can be as little as 6 decimal digits.

The appropriate floating-point type to use depends on the nature and range of values you need to work with in your code. In situations where either type would be appropriate, Double is preferred.

Comments

1

Precision

  • Float - 32-bit (7 digits) floating point precision
  • Double - 64-bit (15 digits) floating point precision
  • One bit is allocated for signed bit.

Memory requirement

  • Float - 4 bytes
  • Double - 8 bytes

Range

  • Float - within 1.2E-38 to 3.4E+38
  • Double - within 2.3E-308 to 1.7E+308

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.