getting 0.0000 when converting NSString value to float

♀尐吖头ヾ 提交于 2019-12-08 13:43:17

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!