问题
In my application, i tried to convert NSString value to float using
NSString *value = [dict objectForKey:@"student_Percentage"];
float f = [value floatValue];
But I'm getting the value of f as 0.00000. I tried with NSNumberFormatter, NSNumber... but still get 0.00000.
回答1:
floatValue returns 0.0 if the receiver doesn’t begin with a valid text representation of a floating-point number.
[dict objectForKey:@"student_Percentage"] value should be like 8.9.
Remove double quotes from your string.
NSMutableString *value = [dict objectForKey:@"student_Percentage"];
[value replaceOccurrencesOfString:@"\"" withString:@"" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [value length])];
float f = [value floatValue];
回答2:
Hey i think your dict value has a problem. Try this code it gives the correct value.
NSString *temp = @"25.38";
float p = [temp floatValue];
NSLog(@"%f",p);
Or maybe use valueforkey instead of objectForKey.
来源:https://stackoverflow.com/questions/11624900/getting-0-0000-when-converting-nsstring-value-to-float