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

4

13

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

Lodie answered 21/7, 2010 at 12:34 Comment(0)
D
37
double cal = [value doubleValue] + ([value2 doubleValue] * 8) + 3;
NSString *message =[[NSString alloc] initWithFormat:@"%f",cal];
Diatessaron answered 21/7, 2010 at 12:38 Comment(4)
Now that is just completely subjectiveDiatessaron
I looked around and so far %f and %g seem to be identical according to most references. How are they different?Valise
@tc. what's wrong with you? That's subjective, don't be arrogant. +1 for compensation.Neibart
%g will not give you 300 digits of output unless you ask for it.Arena
A
3

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.

Arena answered 21/7, 2010 at 13:9 Comment(1)
Thanks for that but i just needed upto 2 decimals places .. ie : 12.50Lodie
S
1
double cal = [value doubleValue] + ([value2 doubleValue] * 8) + 3;
NSString *message =[[NSString alloc] initWithFormat:@"%g",cal];

// do work with message

[message release];
Swithbert answered 21/7, 2010 at 12:44 Comment(0)
P
1

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];
Phalarope answered 2/10, 2013 at 17:14 Comment(2)
why the pointer? It should be double cost = [string doubleValue];Herriot
good point. on a meta level... why the comment? just edit the post? :DPhalarope

© 2022 - 2024 — McMap. All rights reserved.