10

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?

Duck
  • 34,902
  • 47
  • 248
  • 470

5 Answers5

41

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.

Jasarien
  • 58,279
  • 31
  • 157
  • 188
  • both methods - yours and mipadi's - are perfect for the conversion, but for some reason, mipadi's gave me a string that was slightly different of the original number. Your's give me the same number... thanks. – Duck Mar 18 '10 at 16:27
23
[NSString stringWithFormat:@"%.20f", myDouble];

or

@(myDouble).stringValue;
Hafthor
  • 16,358
  • 9
  • 56
  • 65
13

You can pass a width format specifier to stringWithFormat.

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

will format myDouble with 20 decimal places.

mipadi
  • 398,885
  • 90
  • 523
  • 479
  • thanks!!! Just a final question. Is this the only way to convert a double to string? I mean, using stringWithFormat? – Duck Mar 18 '10 at 16:04
  • 1
    @Hafthor: No need for `lf`. `f` is the format specifier for a double, as noted in the Cocoa string documentation (https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Strings/Articles/formatSpecifiers.html#//apple_ref/doc/uid/TP40004265) and this question (http://stackoverflow.com/a/4264154/28804). – mipadi Jan 27 '14 at 18:10
2

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

Use this for no decimal value

Anand Mishra
  • 1,093
  • 12
  • 15
2

There's also NSNumberFormatter.

Peter Hosey
  • 95,783
  • 15
  • 211
  • 370