2012-10-17 40 views
0

你好,我想知道如何讓我的NSString閱讀5.11爲5.11而不是5.1。 我可以做到這一點是必要的,我正在從這個領域閱讀英尺和英寸,而不是十進制格式。此代碼適用於計算NSString輸入轉換目標c

CGFloat hInInches = [height floatValue]; 
    CGFloat hInCms = hInInches *0.393700787; 
    CGFloat decimalHeight = hInInches; 
    NSInteger feet = (int)decimalHeight; 
    CGFloat feetToInch = feet*12; 
    CGFloat fractionHeight = decimalHeight - feet; 
    NSInteger inches = (int)(12.0 * fractionHeight); 
    CGFloat allInInches = feetToInch + inches; 
    CGFloat hInFeet = allInInches; 

但它不允許您以正確的方式讀取從nstextfield中獲取的值。

任何幫助獲得這從nstextfield正確的信息讀取,將不勝感激。 感謝你

+2

哪裏的任何這裏處理字符串的代碼?我沒有看到發佈的代碼的任何相關性。 – Eiko

回答

0

你可以調用doubleValue方法來得到一個精確的值。

NSString *text = textField.text; 
double value = [text doubleValue]; 
0

如果我理解這個權利,你想要做的是有一個用戶在被解讀爲一個NSString的輸入輸入「5.11」,並且希望它的意思是「五英尺11英寸」而不是「5英尺加0.11英尺」(約5英尺1)。

作爲一個方面說明,我建議從UI的角度來看這個。這就是說...如果你想這樣做,獲取「英尺」和「英寸」所需值的最簡單方法是直接從NSString中獲取它們,而不必等到轉換它們數字。浮點數不是一個精確的數值,如果您試圖假設浮點數是小數點兩邊的兩個整數,則可能會遇到問題。

相反,試試這個:

NSString* rawString = [MyNSTextField stringValue]; // "5.11" 
NSInteger feet; 
NSInteger inches; 

// Find the position of the decimal point 

NSRange decimalPointRange = [rawString rangeOfString:@"."]; 

// If there is no decimal point, treat the string as an integer 

if(decimalPointRange.location == NSNotFound) { 
    { 
    feet = [rawString integerValue]; 
    inches = 0; 
    } 

// If there is a decimal point, split the string into two strings, 
// one before and one after the decimal point 

else 
    { 
    feet = [[rawString substringToIndex:decimalPointRange.location] integerValue]; 
    inches = [[rawString substringFromIndex:(decimalPointRange.location + 1)] integerValue]; 
    } 

您現在有英尺和英寸的整數值,而你想要做的轉換其餘的都是小事從這一點:

NSInteger heightInInches = feet + (inches * 12); 
CGFloat heightInCentimeters = (heightInInches * 2.54);