将字符串分数转换为十进制

时间:2011-11-03 16:49:01

标签: iphone objective-c

我有一个plist文件,我正在读出一个测量值,但有些测量值是6 3/8“的分数。我按照这种方式对它们进行了格式化,因为它更容易在卷尺上找到它而不是它找到6.375“。我现在的问题是我想在飞行中转换为公制,而不是读取数字的小数部分。我目前的代码就是这个。

cutoutLabel.text = [NSString stringWithFormat:@"%.2f mm. %@", [[[sizeDict valueForKey:Sub_Size] objectForKey:@"Cutout Dimensions"]floatValue] * 25.4, [temp objectAtIndex:2]];

感谢。

3 个答案:

答案 0 :(得分:4)

这就是我最终做的事情。

NSArray *temp = [[[sizeDict valueForKey:Sub_Size] objectForKey:@"Cutout Dimensions"] componentsSeparatedByString:@" "];
        if ([temp count] > 2) {
            NSArray *fraction = [[temp objectAtIndex:1]componentsSeparatedByString:@"/"];
            convertedFraction = [[fraction objectAtIndex:0]floatValue]/[[fraction objectAtIndex:1]floatValue];
        }

答案 1 :(得分:1)

您可以按如下方式获得分子和分母:

NSRange slashPos = [fraction.text rangeOfString:@"/"];

NSString * numerator = [fraction.text substringToIndex:slashPos.location];
NSString * denominator = [fraction.text substringFromIndex:slashPos.location+1];

你应该多加照顾, 检查您的范围是否为1,并确保该字符串在“/”字符后面包含字符。但是,如果你知道你正在为这段代码提供一个分数字符串,它应该适用于你的情况

这个想法已经到位,但您还需要首先应用相同的逻辑来将整数与分数分开。应用相同的逻辑,搜索@“”,然后找到分子和分母

答案 2 :(得分:0)

在伊恩的答案基础上,并尝试更完整(因为他的例子是一个整数和一个英寸字符(6 3/8“)的小数部分,我建议以下方法(它也适用于那里是整数之前的空格:

// Convert a string consisting of a whole and fractional value into a decimal number
-(float) getFloatValueFromString: (NSString *) stringValue {

// The input string value has a format similar to 2 1/4". Need to remove the inch (") character and
// everything after it.
NSRange found = [stringValue rangeOfString: @"\""];    // look for the occurrence of the " character
if (found.location != NSNotFound) {
    // There is a " character. Get the substring up to the "\"" character
    stringValue = [stringValue substringToIndex: found.location];
}

// Now the input format looks something like 2 1/4. Need to convert this to a float value
NSArray *temp = [stringValue componentsSeparatedByString:@" "];
float convertedFraction = 0;
float wholeNumber = 0;
for (int i=0; i<[temp count]; i++) {
    if ([[temp objectAtIndex:i] isEqualToString:@""]) {
        continue;
    }
    NSArray *fraction = [[temp objectAtIndex:i]componentsSeparatedByString:@"/"];
    if ([fraction count] > 1) {
        convertedFraction = [[fraction objectAtIndex:0]floatValue]/[[fraction objectAtIndex:1]floatValue];
    }
    else if ([fraction count] == 1) {
        wholeNumber = [[fraction objectAtIndex:0] floatValue];
    }
}

convertedFraction += wholeNumber;

return convertedFraction;
}