将具有多个点的字符串转换为float或int?

时间:2014-04-13 13:45:18

标签: ios objective-c

我希望将类似5.9.1的数字转换为float或int值,以将其与其他值进行比较

1 个答案:

答案 0 :(得分:0)

使用stringByReplacingOccurrencesOfString:withString:

NSString *dottedNumber = @"5.9.1";
NSString *undottedNumber = [dottedNumber stringByReplacingOccurrencesOfString:@"." withString:@""];
// undottedNumber will now be '591'
CGFloat number = [[@"0." stringByAppendingString:undottedNumber] floatValue];

然后会给您0.591,但是根据您最近的评论,您希望比较版本字符串,这不是一项简单的任务。但这应该(可能!)涵盖大多数情况。

无论本地化为floatValue状态如何,这都将有效:

  

此方法使用存储在非本地化值中的格式信息   因此,您不必担心千位分隔符的使用期限!

注意:如果您想将5.12.15.2.0进行比较,则不会有效,因为0.5121小于0.520

要解决此问题,您需要将其分解为组件,并通过使用0 s填充确保点之间的每个段具有相同的长度,即将5.2.0转换为{ {1}}。

5.02.0

示例输出:

+(BOOL)isVersion:(NSString *)version laterThanVersion:(NSString *)anotherVersion
{

     NSMutableArray *versionComponents = [[version componentsSeparatedByString:@"."] mutableCopy];
     NSMutableArray *anotherVersionComponents = [[anotherVersion componentsSeparatedByString:@"."] mutableCopy];

     for (NSUInteger i=0; i<MAX([versionComponents count], [anotherVersionComponents count]); i++) {
         NSString *component = nil;
         NSString *anotherComponent = nil;

         if (i < [versionComponents count]) {
             component = versionComponents[i];
         }
         if (i < [anotherVersionComponents count]) {
             anotherComponent = anotherVersionComponents[i];
         }

         NSString *formatString = @"%%0%dd";
         if ([component length] > [anotherComponent length]) {
             // Pad out anotherComponent
             anotherComponent = [NSString stringWithFormat:[NSString stringWithFormat:formatString, [component length]], [anotherComponent integerValue]];
         } else {
             // Pad out component
             component = [NSString stringWithFormat:[NSString stringWithFormat:formatString, [anotherComponent length]], [component integerValue]];
         }

         if (i < [versionComponents count]) {
             versionComponents[i] = component;
         }
         if (i < [anotherVersionComponents count]) {
             anotherVersionComponents[i] = anotherComponent;
         }
     }

     NSInteger versionInt = [[versionComponents componentsJoinedByString:@""] integerValue];
     NSInteger anotherVersionInt = [[anotherVersionComponents componentsJoinedByString:@""] integerValue];

     return versionInt > anotherVersionInt;
}