147

I want to convert a string into a double and after doing some math on it, convert it back to a string.

How do I do this in Objective-C?

Is there a way to round a double to the nearest integer too?

Alexander Abakumov
  • 13,617
  • 16
  • 88
  • 129
rksprst
  • 6,471
  • 18
  • 54
  • 81

12 Answers12

235

You can convert an NSString into a double with

double myDouble = [myString doubleValue];

Rounding to the nearest int can then be done as

int myInt = (int)(myDouble + (myDouble>0 ? 0.5 : -0.5))

I'm honestly not sure if there's a more streamlined way to convert back into a string than

NSString* myNewString = [NSString stringWithFormat:@"%d", myInt];
jjnguy
  • 136,852
  • 53
  • 295
  • 323
olliej
  • 35,755
  • 9
  • 58
  • 55
  • 13
    You don't necessarily want to do this, because different locales format numbers differently. Some will write "1000" for one thousand, while others will write "1,000" and others "1.000" - which do you get from -[NSString doubleValue]? – Chris Hanson Oct 04 '08 at 19:06
  • 9
    Double is a numeric data type - it does not contain any formatting. Calling [NSString doubleValue] would return 1000 because it's just a number. – Andy Oct 05 '08 at 12:53
  • 12
    And an NSString cannot contain a number, only a representation of a number. That representation may be in any of a variety of formats that differ by locale. – Chris Hanson Oct 06 '08 at 06:08
  • 5
    you might want to integrate @Barry Wark's answer in yours, `[[NSNumber numberWithInt:myInt] stringValue]` – Dan Rosenstark Mar 18 '11 at 17:29
  • 1
    What if the string value isn't a valid double string, then 0.0 will be returned by doubleValue. It seems to me that the solution suggesting the use of NSNumberFormatter is better because if the string doesn't represent a valid double string, then nil is returned. – Kaydell Nov 07 '14 at 22:00
  • I'm with @Kaydell here, it seems like this solution makes it impossible to do any kind of real error handling in the cases where the string can't be parsed as a double (because 0.0 is a valid and reasonable double), which would severely limit the amount of applications this strategy can handle. – jrh Jan 23 '19 at 02:25
71

To really convert from a string to a number properly, you need to use an instance of NSNumberFormatter configured for the locale from which you're reading the string.

Different locales will format numbers differently. For example, in some parts of the world, COMMA is used as a decimal separator while in others it is PERIOD — and the thousands separator (when used) is reversed. Except when it's a space. Or not present at all.

It really depends on the provenance of the input. The safest thing to do is configure an NSNumberFormatter for the way your input is formatted and use -[NSFormatter numberFromString:] to get an NSNumber from it. If you want to handle conversion errors, you can use -[NSFormatter getObjectValue:forString:range:error:] instead.

Kenly
  • 24,317
  • 7
  • 44
  • 60
Chris Hanson
  • 54,380
  • 8
  • 73
  • 102
  • 2
    Or you can use a localised scanner, for example one created with [NSScanner localizedScannerWithString:], and then [scanner scanDouble:&aDouble] will scan in a double based on the user's current locale. – dreamlax Jun 07 '09 at 11:17
33

Adding to olliej's answer, you can convert from an int back to a string with NSNumber's stringValue:

[[NSNumber numberWithInt:myInt] stringValue]

stringValue on an NSNumber invokes descriptionWithLocale:nil, giving you a localized string representation of value. I'm not sure if [NSString stringWithFormat:@"%d",myInt] will give you a properly localized reprsentation of myInt.

Barry Wark
  • 107,306
  • 24
  • 181
  • 206
8

Here's a working sample of NSNumberFormatter reading localized number String (xCode 3.2.4, osX 10.6), to save others the hours I've just spent messing around. Beware: while it can handle trailing blanks such as "8,765.4 ", this cannot handle leading white space and this cannot handle stray text characters. (Bad input strings: " 8" and "8q" and "8 q".)

NSString *tempStr = @"8,765.4";  
     // localization allows other thousands separators, also.
NSNumberFormatter * myNumFormatter = [[NSNumberFormatter alloc] init];
[myNumFormatter setLocale:[NSLocale currentLocale]]; // happen by default?
[myNumFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
     // next line is very important!
[myNumFormatter setNumberStyle:NSNumberFormatterDecimalStyle]; // crucial

NSNumber *tempNum = [myNumFormatter numberFromString:tempStr];
NSLog(@"string '%@' gives NSNumber '%@' with intValue '%i'", 
    tempStr, tempNum, [tempNum intValue]);
[myNumFormatter release];  // good citizen
miker
  • 189
  • 2
  • 7
  • 1
    What does numberFromString return if the string is *not* a valid string? – Ben Clayton Sep 04 '12 at 10:00
  • numberFromString: returns an NSNumber object. See [NumberFormatting](http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/DataFormatting/Articles/dfNumberFormatting10_4.html) and [NSNumberFormatter](http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSNumberFormatter_Class/Reference/Reference.html) in apple docs. (I'm not sure how NSNumber objects encode "not a number" or "bad number", but I see there is a NSNull possible value.) – miker Nov 29 '12 at 17:00
  • @BenClayton numberFromString returns a `nil` valued `NSNumber*` if it can't be parsed. I can't reproduce that problem you had with leading white space and stray text characters, IMO it's working properly. `" 28.5 "` parses as 28.5, and `"gibberish28.5"`, `"28.5gibberish"`, and `"gibberish28.5gibberish"` are all unparseable; `" 2 8 . 5. "` is unparsable but that's not unusual. – jrh Jan 23 '19 at 03:08
7

olliej's rounding method is wrong for negative numbers

  • 2.4 rounded is 2 (olliej's method gets this right)
  • −2.4 rounded is −2 (olliej's method returns -1)

Here's an alternative

  int myInt = (int)(myDouble + (myDouble>0 ? 0.5 : -0.5))

You could of course use a rounding function from math.h

Paul Dixon
  • 295,876
  • 54
  • 310
  • 348
3
// Converting String in to Double

double doubleValue = [yourString doubleValue];

// Converting Double in to String
NSString *yourString = [NSString stringWithFormat:@"%.20f", doubleValue];
// .20f takes the value up to 20 position after decimal

// Converting double to int

int intValue = (int) doubleValue;
or
int intValue = [yourString intValue];
Fahim Parkar
  • 30,974
  • 45
  • 160
  • 276
Samir Jwarchan
  • 1,027
  • 11
  • 14
3

For conversion from a number to a string, how about using the new literals syntax (XCode >= 4.4), its a little more compact.

int myInt = (int)round( [@"1.6" floatValue] );

NSString* myString = [@(myInt) description];

(Boxes it up as a NSNumber and converts to a string using the NSObjects' description method)

Robert
  • 37,670
  • 37
  • 171
  • 213
2

For rounding, you should probably use the C functions defined in math.h.

int roundedX = round(x);

Hold down Option and double click on round in Xcode and it will show you the man page with various functions for rounding different types.

benzado
  • 82,288
  • 22
  • 110
  • 138
1

I ended up using this handy macro:

#define STRING(value)               [@(value) stringValue]
Neeku
  • 3,646
  • 8
  • 33
  • 43
dimanitm
  • 101
  • 1
  • 3
1

convert text entered in textfield to integer

double mydouble=[_myTextfield.text doubleValue];

rounding to the nearest double

mydouble=(round(mydouble));

rounding to the nearest int(considering only positive values)

int myint=(int)(mydouble);

converting from double to string

myLabel.text=[NSString stringWithFormat:@"%f",mydouble];

or

NSString *mystring=[NSString stringWithFormat:@"%f",mydouble];

converting from int to string

myLabel.text=[NSString stringWithFormat:@"%d",myint];

or

NSString *mystring=[NSString stringWithFormat:@"%f",mydouble];
Ashish P
  • 1,463
  • 1
  • 20
  • 29
1

from this example here, you can see the the conversions both ways:

NSString *str=@"5678901234567890";

long long verylong;
NSRange range;
range.length = 15;
range.location = 0;

[[NSScanner scannerWithString:[str substringWithRange:range]] scanLongLong:&verylong];

NSLog(@"long long value %lld",verylong);
Richard J. Ross III
  • 55,009
  • 24
  • 135
  • 201
zoltan
  • 41
  • 3
1

This is the easiest way I know of:

float myFloat = 5.3;
NSInteger myInt = (NSInteger)myFloat;
Sam Soffes
  • 14,831
  • 9
  • 76
  • 80