Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cocoa - converting a double to string

I have a double number and I would like to convert it to string.

The number is, for example, something like

24.043333332154465777...

but if I convert it to string using something like

NSString *myString = [NSString stringWithFormat:@"%f", myDouble];

The string is just

24.043333

how do I get a full string the corresponds to the whole double number? What other methods do I have to convert this?

like image 584
Duck Avatar asked Mar 18 '10 15:03

Duck


3 Answers

[NSString stringWithFormat:@"%.20f", myDouble];

or

@(myDouble).stringValue;
like image 187
Hafthor Avatar answered Oct 24 '22 11:10

Hafthor


Another option, since you asked for other ways in your comment to mipadi's answer:

Create an NSNumber using NSNumber *myDoubleNumber = [NSNumber numberWithDouble:myDouble];

Then call [myDoubleNumber stringValue];

From the docs:

Returns the receiver’s value as a human-readable string, created by invoking descriptionWithLocale: where locale is nil.

like image 37
Jasarien Avatar answered Oct 24 '22 09:10

Jasarien


You can pass a width format specifier to stringWithFormat.

NSString *myString = [NSString stringWithFormat:@"%.20f", myDouble];

will format myDouble with 20 decimal places.

like image 43
mipadi Avatar answered Oct 24 '22 10:10

mipadi