views:

96

answers:

2

Hi

I would guess it's the simplest thing but it's really confusing me. I'm sure I've successfully used doubles before but now I'm having trouble.

I just made a new 'test' project to see if I can get it working, but all I'm trying to do is set a double value.

So in the View Controller's viewDidLoad i've typed:

double z = 2938.09;
NSLog(@"z = %d", z);

I would expect it to output 'z = 2938.09' but instead I get 'z = 343597384'

double z = 3.4 returns z = 858993459

Also most integer values report back as z = 0, however not always (sometimes another strange number as above is spewed out)

Am I missing something here or it something strange going on??

Even tried stuff like

NSString *newString = [[NSString alloc] initWithString:@"3.4"];
double z = [newString.text doubleValue];
NSLog(@"z = %d", z);
[newString release];

but still get the crazy z = 858993459 :(

+1  A: 

For printing the Double value use %f instead of %d.

NSlog format specifiers

%@ Object

%d, %i signed int

%u unsigned

%f float/double

%x, %X hexadecimal int

%o octal

%zu size_t

%p pointer

%e float/double (in scientific notation)

%g float/double (as %f or %e, depending on value)

%s C string (bytes)

%S C string (unichar)

%.*s Pascal string (requires two arguments, pass pstr[0] as the first, pstr+1 as the second)

%c character

%C unichar

%lld long long

%llu unsigned long long

%Lf long double

Warrior
Ahh - what a beautiful sight it is to see z = 3.400000! Thanks guys, now I can get stuck into my proper code and hopefully sort things out.Tv
Tris
+2  A: 

Double is a double precision float, and so, to print you should use the same way used to print floats:

NSString *newString = [[NSString alloc] initWithString:@"3.4"];
double z = [newString.text doubleValue];
NSLog(@"z = %f", z);
[newString release];

%d is used to print signed int.

Have a look at this link with the format specifiers for NSLog: http://www.cocoadev.com/index.pl?NSLog

vfn
Ahh - what a beautiful sight it is to see z = 3.400000! Thanks guys, now I can get stuck into my proper code and hopefully sort things out.Tv
Tris