0

I really confused about a experience I've made today. I was calculating the cell height.

This is the code:

float height = [text sizeWithFont:[UIFont systemFontOfSize:17.0f] constrainedToSize:CGSizeMake(300 - width - 20.0, CGFLOAT_MAX) lineBreakMode:UILineBreakModeWordWrap].height;

Now the thing is, when I change the ...systemFontOfSize:17.0f to ...systemFontOfSize:17.0, so without "f" it calculate a wrong height.

My question is more about what this "f" stands for and what it does.

Monolo
  • 18,205
  • 17
  • 69
  • 103
  • Because Objective-C comes from C/C++ you will find the answer (http://stackoverflow.com/questions/5026570/suffix-of-f-on-float-value) – Black Frog Sep 13 '12 at 20:01

3 Answers3

2

It tells the computer that this is a floating point number. If there is no f after the number, it is considered a double or an integer (depending on if there is a decimal or not).

20.0f -> float
20.0 -> double
20 -> integer
miho
  • 11,765
  • 7
  • 42
  • 85
2

Well, this is really bizarre because by definition C passes floats as doubles on the stack, and since ObjC methods get turned into C functions, even with a float parameter the float is extended to a double. All that said, its possible the compiler is putting the 17.0 into a float, then extended it to a double, and somehow iOS is looking at that exact binary number (comparing it), whereas if you pass a double directly, it is slightly different and ends up as a fractional font.

So I got curious and decided to try a test:

- (void)test:(float)foo
{
    union {
        float f;
        uint32_t u;
    } u;

    u.f = foo;
    NSLog(@"foo=%.15f hex=%x", u.f, u.u);
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    [self test:17.0];
    [self test:17.0f];

Output:

2012-09-13 16:02:34.035 Searcher[73472:f803] foo=17.000000000000000 hex=41880000
2012-09-13 16:02:34.036 Searcher[73472:f803] foo=17.000000000000000 hex=41880000

The numbers were exactly the same, same as the hex. Something is obviously wrong elsewhere in your code.

David H
  • 40,852
  • 12
  • 92
  • 138
1

The f suffix simply tells the compiler which is a float and which is a double. Without 'f' all calculations will be of double's precision.

1.0f float

1.0 double

msk
  • 8,885
  • 6
  • 41
  • 72