Convert int to CGFloat

62,758

Solution 1

In the past casting a CGFloat value using the () syntax has worked fine for me. CGFloat is just defined as "typedef float CGFloat;" so you go about casting it the same way you would a float:

CGFloat f = (CGFloat)intVal;

or, if your value is a constant:

CGFloat f = 1.10;

Solution 2

i was searching in how to do the same in swift and i find the question in first result (high ranked) so i will post the answer if had found in case someone was lucky like me :)

let myCGFloat = CGFloat(myFloat)
Share:
62,758
Shoaibi
Author by

Shoaibi

I code therefore i am.

Updated on October 08, 2020

Comments

  • Shoaibi
    Shoaibi over 3 years

    Any idea on how to convert an int to CGFloat in Objective-C?

  • Gavin Brock
    Gavin Brock about 14 years
    Sadly this no longer works on 64bit, where a CGFloat is a 'double': stackoverflow.com/questions/1264924/…
  • Joe D
    Joe D almost 14 years
    If you remove the f suffix then it should work, there will be an implicit downcast from double to float on a 32-bit platform and no cast at all on a 64-bit one.
  • Anton Duzenko
    Anton Duzenko almost 3 years
    Expression took 37ms to type-check (limit: 33ms)
  • Anton Duzenko
    Anton Duzenko almost 3 years
    Swift compiler takes 30+msec to compile this
  • AntonTheDev
    AntonTheDev over 2 years
    @AntonDuzenko how did you get around this to bring down the type check
  • Anton Duzenko
    Anton Duzenko over 2 years
    @AntonTheDev I didn't. It's still polluting my code. You can increase time threshold to be higher than your slowest type check or move your logic to an obj-c or c++ code. I'm running a MacOS VM - maybe native M1 environment is much faster.
  • Amr Angry
    Amr Angry over 2 years
    @AntonDuzenko I don't know how you measure the time, it will be nice if you let us know.
  • Anton Duzenko
    Anton Duzenko over 2 years
    -warn-long-expression-type-checking