Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert NSString to double for calculations and then back again to print in NSString

I accept NSString as

NSString *value = [valuelist objectAtIndex:valuerow];
NSString *value2 = [valuelist2 objectAtIndex:valuerow2];

from UIPickerView. I want to

double *cal = value + (value2 * 8) + 3;


NSString *message =[[NSString alloc] initWithFormat:@"%@",cal];

I should be able to get the string in message after I do the calculations on it .. Please help My program is crashing

like image 624
Omkar Jadhav Avatar asked Jul 21 '10 12:07

Omkar Jadhav


4 Answers

double cal = [value doubleValue] + ([value2 doubleValue] * 8) + 3;
NSString *message =[[NSString alloc] initWithFormat:@"%f",cal];
like image 183
Joshua Weinberg Avatar answered Oct 21 '22 18:10

Joshua Weinberg


You shouldn't convert between doubles and strings all the time, since it tends to lose accuracy (in general, you have to be very careful if you don't want to lose accuracy).

For example, nextafter(1.0,2.0) returns the smallest double larger than 1 (exactly 1.0000000000000002220446049250313080847263336181640625, but we're happy with 1.0000000000000002). Formatting with "%g" just returns "1".

We'd expect NSNumber to do the right thing, but [[NSNumber numberWithDouble:nextafter(1,2)] stringValue] also returns "1". According to the docs, -[NSNumber stringValue] calls [self descriptionWithLocale:nil] which formats it with "%0.16g". That's not enough. We get the right answer by formatting with "%.17g", though. I think "%.17g" is enough provided that doubles are IEEE 754 64-bit doubles and the libraries are working properly, but there's no guarantee.

At the end of the day, there's no guarantee that [[NSString stringWithFormat:@"%.17g",n] doubleValue] == n.

like image 24
tc. Avatar answered Oct 21 '22 17:10

tc.


double cal = [value doubleValue] + ([value2 doubleValue] * 8) + 3;
NSString *message =[[NSString alloc] initWithFormat:@"%g",cal];

// do work with message

[message release];
like image 1
taskinoor Avatar answered Oct 21 '22 17:10

taskinoor


Posting a new answer since the accepted one only does string=>double:

double cal = [value doubleValue] + ([value2 doubleValue] * 8) + 3;
NSString *message =[[NSString alloc] initWithFormat:@"%f",cal];

To go double=>string, use

double cost = [string doubleValue];
like image 1
pfrank Avatar answered Oct 21 '22 16:10

pfrank