2011-11-03 56 views
2

我有我讀出測量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]]; 

謝謝。

+0

只存儲度量版以及老式的和搗毀版 –

+0

我希望避免這種情況,大約有75項,我將不得不 –

+1

只需將它們輸入Google,或者讓一個實習生完成它,這將需要大約5到10分鐘的時間,我認爲另一種方法是將f ind(或編寫你自己的)庫來解析分數,這將花費更長的時間。 –

回答

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

你可以得到的分子和分母如下:

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

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

你應該採取更多的照顧比這 檢查你的範圍是長度爲1和後確保字符串具有字符「/ 「性格。但如果你知道你是餵養這個代碼的一小部分字符串應該在你的情況

的想法是在工作的地方,但你也需要先申請相同的邏輯來整個數量從你部分分開。應用相同的邏輯,搜索@「」,然後找到分子和分母

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; 
} 
相關問題