7

How to print a float in Objective-C as, for example, 3.45 instead of 3.45555555555?

exebook
  • 32,014
  • 33
  • 141
  • 226
  • possible duplicate of [how to set the float value to two decimal number in objective C](http://stackoverflow.com/questions/560517/how-to-set-the-float-value-to-two-decimal-number-in-objective-c) – jscs Mar 02 '12 at 21:08

2 Answers2

23

Try formatting the float like this:

NSLog(@"%.2f", myFloat);

The % sign means this will be replaced by the corresponding argument following (myFloat). The .2 means 2 decimal places, and f means a float datatype.

Take a look here for more detail.

Objective-C's NSLog is very similar to C's printf, with the main exceptions being that you must use an Objective-C string literal (@"…") and you should use %@ for Objective-C strings (NSStrings) rather than %s, which is for "Plain C strings".

mk12
  • 25,873
  • 32
  • 98
  • 137
sch
  • 27,436
  • 3
  • 68
  • 83
3

Depends on how you're printing it. If you want to show it in a GUI (which is probably the common case for Cocoa and Cocoa Touch apps), use an NSNumberFormatter and set it to have two decimal places. If you're printing it through NSLog() or printf(), you'd use a format specifier along the lines of "%.2f".

Chuck
  • 234,037
  • 30
  • 302
  • 389