views:

128

answers:

3

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

+2  A: 
double cal = [value doubleValue] + ([value2 doubleValue] * 8) + 3;
NSString *message =[[NSString alloc] initWithFormat:@"%f",cal];
Joshua Weinberg
Thankyou Guys ! It worked !
Downvote for using "%f". "%g" is better in almost every case.
tc.
Now that is just completely subjective
Joshua Weinberg
I looked around and so far %f and %g seem to be identical according to most references. How are they different?
jamone
%g will do scientific notation %f will always do fixed point
Joshua Weinberg
A: 
double cal = [value doubleValue] + ([value2 doubleValue] * 8) + 3;
NSString *message =[[NSString alloc] initWithFormat:@"%g",cal];

// do work with message

[message release];
taskinoor
A: 

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.

tc.
Thanks for that but i just needed upto 2 decimals places .. ie : 12.50