Sekhar
Sekhar

Reputation: 339

changing a string to double returning one

I have stored a value 1/129600.0 in a plist as a string. I am able to retrieve it as a string but when i am trying to convert it as a double i am getting it as 1.0.I have also tried CFString

NSString *value = [[self array]objectAtIndex:m];
double a = [value doubleValue];
NSLog(@"%@",value);
NSLog(@"%f",a);

and in log the returned values are 1/129600.0 and 1.0

Upvotes: 2

Views: 165

Answers (4)

Tieme
Tieme

Reputation: 65389

I guess 1/129600.0 is not a valid number.

Try to create an expression and create an NSNumber from it:

NSString *equation = [[self array]objectAtIndex:m];
NSNumber *a = [[NSExpression expressionWithFormat:equation] expressionValueWithObject:nil context:nil];
double a = [result doubleValue];
NSLog(@"%f", a);

Upvotes: 2

Giuseppe Mosca
Giuseppe Mosca

Reputation: 1333

This code works fine, I tried it in xCode:

NSString *equation = [[self array]objectAtIndex:m];
NSExpression *result = [NSExpression expressionWithFormat:equation];

NSNumber *a = [result expressionValueWithObject:nil context: nil];

NSLog(@"%@",result);
NSLog(@"%.10f",[a doubleValue]);

Upvotes: 2

Inder Kumar Rathore
Inder Kumar Rathore

Reputation: 39988

Try this

NSString *value = [[self array]objectAtIndex:m];
NSArray *arr = [value componentsSeparatedByString:@"/"];
double a;
if ([arr count] == 2)
{
   a = [arr objectAtIndex:0]/[arr objectAtIndex:1];
}
NSLog(@"%@",value);
NSLog(@"%f",a);

Upvotes: 0

Amadan
Amadan

Reputation: 198324

1/129600.0 is not a valid representation for a number in most programming languages, including ObjC. You need to parse the string and interpret it yourself.

Upvotes: 1

Related Questions