PDA

View Full Version : Convert a double into a string




ricku425
Feb 20, 2008, 11:43 AM
I am totally new to the whole Obj-C/XCode/IB world, and at the moment, I'm just playing around with some simple i/o stuff. I am wanting to put a double value number into a string. Here's the code I'm trying to use at the moment:

double value = 123.45678901;
NSString *myString = [NSString stringWithFormat:@"You're double value is %d", value];
[outputTextField setString:myString];

The output, however, shows up as "You're double value is 133744594".

Is it possible to do what I'm trying to do? I've been able to get all the other data types to work (namely int and float) as I would expect them to behave.

Any help for this complete noob would be appreciated...



toddburch
Feb 20, 2008, 11:46 AM
Instead of %d, try %lf (that's ell, eff).

%d in C/C++ is for integers. %f is for floats. %lf is for doubles.

Todd

ricku425
Feb 20, 2008, 12:00 PM
Instead of %d, try %lf (that's ell, eff).

%d in C/C++ is for integers. %f is for floats. %lf is for doubles.

Todd

Todd-

Thanks you so much for your reply. That got me half way there (well, technically 82% of the way...). By replacing %d with %lf, the output printed as: "You're double value is 123.456789". However, my double value is actually 123.45678901. That's not too many decimal places for a double value, is it?

toddburch
Feb 20, 2008, 12:16 PM
I believe you get 6 decimal positions by default. Try %.8lf.

Todd

ricku425
Feb 20, 2008, 01:03 PM
I believe you get 6 decimal positions by default. Try %.8lf.

Todd

Awesome! I looked in FOUR Obj-C programming books and couldn't find that anywhere! Thanks for the super-quick help!!

kainjow
Feb 20, 2008, 01:16 PM
Awesome! I looked in FOUR Obj-C programming books and couldn't find that anywhere! Thanks for the super-quick help!!

The Apple documentation is usually the best place to look for small things like this: String Format Specifiers (http://developer.apple.com/documentation/Cocoa/Conceptual/Strings/Articles/formatSpecifiers.html)

toddburch
Feb 20, 2008, 01:42 PM
Awesome! I looked in FOUR Obj-C programming books and couldn't find that anywhere! Thanks for the super-quick help!!

That is amazing, because I can't even spell Ojbective-C. Yet.