开发者

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 + (开发者_Python百科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


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


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.


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

// do work with message

[message release];


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜