views:

68

answers:

3

When I do the following, the output is an integer value:

double myvar = fabs(-5.01);
NSLog(@"%.f", myvar);

Should it be 5.01?

A: 

What is the output? Have you tried @"%f"? But yes. It should return 5.01. There's a chance the precision may be off since it's floating point, though.

Matt Williamson
+10  A: 

The . (with no number after it) in "%.f" means format with a precision of 0 (which for floats, means round to the nearest integer). You probably just want "%f"

See http://www.cplusplus.com/reference/clibrary/cstdio/printf/ for a description of the format specifiers (I gather the NSLog format specifiers are a superset of the printf ones)

dave
A: 

Please use

double myvar = fabs(-5.01);
NSLog(@"%.2f", myvar);

As %.f means that after . no value must be there so if you want 2 decimal points you need to write %.2f

hAPPY cODING...

Suriya