How to convert a string into double and vice versa?

Objective C

Objective C Problem Overview


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?

Objective C Solutions


Solution 1 - Objective C

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];

Solution 2 - Objective C

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.

Solution 3 - Objective C

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.

Solution 4 - Objective C

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

Solution 5 - Objective C

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

Solution 6 - Objective C

// 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];

Solution 7 - Objective C

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)

Solution 8 - Objective C

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.

Solution 9 - Objective C

This is the easiest way I know of:

float myFloat = 5.3;
NSInteger myInt = (NSInteger)myFloat;

Solution 10 - Objective C

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);

Solution 11 - Objective C

I ended up using this handy macro:

#define STRING(value)               [@(value) stringValue]

Solution 12 - Objective C

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];

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionrksprstView Question on Stackoverflow
Solution 1 - Objective ColliejView Answer on Stackoverflow
Solution 2 - Objective CChris HansonView Answer on Stackoverflow
Solution 3 - Objective CBarry WarkView Answer on Stackoverflow
Solution 4 - Objective CmikerView Answer on Stackoverflow
Solution 5 - Objective CPaul DixonView Answer on Stackoverflow
Solution 6 - Objective CSamir JwarchanView Answer on Stackoverflow
Solution 7 - Objective CRobertView Answer on Stackoverflow
Solution 8 - Objective CbenzadoView Answer on Stackoverflow
Solution 9 - Objective CSam SoffesView Answer on Stackoverflow
Solution 10 - Objective CzoltanView Answer on Stackoverflow
Solution 11 - Objective CdimanitmView Answer on Stackoverflow
Solution 12 - Objective CAshish PiseyView Answer on Stackoverflow