3

I am new to objective-c. I want to display shorter CGFloat value in NSString. I know in C its easy. But i don't know how to do that in Objective-c. For example,

 CGFloat value = 0.333333;
 NSLog(@"%f%%",value*100);

It will display 33.3333%. But i want to make it 33.33%. How can i do it?

chancyWu
  • 14,073
  • 11
  • 62
  • 81

2 Answers2

7
CGFloat value = 0.333333;
NSLog(@"%.2f%%",value*100);

Will result in 33.33% in the log.

Here is the relevant section from Apple's docs. The Objective-C format specifiers very closely follow (or might even be the same as) those you might know from C. NSLog() automatically accepts format specifiers. To do this with any NSString, use [NSString stringWithFormat:@"myString", arg1, arg2..].

fzwo
  • 9,842
  • 3
  • 37
  • 57
  • 2
    @chancy This is fine for internal use but if you ever need to format such a value for display to the user, do not do this. Instead, use NSNumberFormatter so the number is properly formatted based on the user's locale. – rmaddy Nov 16 '12 at 15:50
0

Or if you want, you can use printf() like in C.

RomanHouse
  • 2,552
  • 3
  • 23
  • 44