views:

59879

answers:

13

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?

+26  A: 

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];
olliej
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
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
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
+3  A: 

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
A: 

Paul is correct, i am a moron -- i just always tend to be dealing with positive values. A more "correct" approach would probably actually be round, lround, or possibly rint -- but they don't exist on all platforms as far as I am aware. But then if you're using Obj-C you're probably on MacOS which does provide them.

olliej
+9  A: 

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
+32  A: 

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.

Chris Hanson
dreamlax
+1  A: 

Further to Chris Hanson's answer, you can find out more about number formatters, their behaviour, and format strings, from NSNumberFormatter on Mac OS X 10.4 in Data Formatting Programming Guide For Cocoa.

mmalc
A: 

Another way to extract numbers from a string is to use an NSScanner: http://developer.apple.com/documentation/Cocoa/Conceptual/Strings/Articles/Scanners.html#//apple_ref/doc/uid/20000147

Graham Lee
+1  A: 

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
+1  A: 

Another source of information that might be useful to you is this article about NSNumberFormatter:

http://www.iphonesdkarticles.com/2008/11/localizing-iphone-apps-part-1.html

jpm
A: 

This is the easiest way I know of:

float myFloat = 5.3;
NSInteger myInt = (NSInteger)myFloat;
Sam Soffes
A: 

Sorry i am beginner. but i have the same problem convert a string to a value.

    NSNumber * zahl = [NSNumberFormatter numberFromString: textField];

    NSLog(@"zahl - ,@",zahl);

gewichtSlider.value = [NSNumber numberWithFloat: zahl];

very simpel text. in the first lain the error is that NSNumberFormatter may not respond to numberFromString ?? which i dont understand because it is a task of the class NSNumberFormatter.

in the third lain there is a error incompatibel type for argument number with float why that. gewichtSlider.value is a slider which has a float.

help would be great ...thanks

abrigado
A: 

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
A: 

@abrigado Your procedure is correct and helpful. Thx!