2014-07-09 39 views
-5

我有一个场景,我正在获取应用程序的版本并将该值转换为double。 我的JSON的值是这种格式'1.0.0',所以当我将它转换为双倍时,它只显示'1'而不是'1.0.0'。 这是我的代码:如何将字符串转换为ios中的浮点值

double appVersion = [[[[NSBundle mainBundle] infoDictionary] 
     objectForKey:@"CFBundleVersion"] doubleValue]; 
NSLog(@"%f",appVersion); 

如何在我的双重价值得到“1.0.0”。 谢谢

+8

“1.0.0”如何可能被解释为双精度? –

+1

为什么你把它转换成双重呢?! – Vatev

回答

4

该应用程序版本的形式major.minor.patchlevel,这不是一个浮点数。相反,您必须阅读完整的字符串并拆分组件,例如:

NSString *appVersion = [[[NSBundle mainBundle] infoDictionary] 
     objectForKey:@"CFBundleVersion"]; 
NSArray *components = [appVersion componentsSeparatedByString:@"."]; 
NSAssert([components count] == 3, @"Something bad happened"); 
unsigned major = [components[0] unsignedValue]; 
unsigned minor = [components[1] unsignedValue]; 
unsigned patchlevel = [components[2] unsignedValue];