2012-05-01 78 views
1

我想在UItextfield的數值輸入上添加一個正/負按鈕,但我無法正常工作。我想要它做的只是從數字輸入的前面添加或刪除一個負號。我能夠做到這一點,但我找不到保持原始小數位數的方法。這是我曾嘗試過的:肯定/否定按鈕無法正常顯示

- (IBAction) negsign 
{ 
    float input = [userinput.text floatValue]; 
    float result = ((input * (-1))); 
    negstring = [NSString stringWithFormat: 
          @"%f", result]; 
    userinput.text = negstring; 
} 

用這個,我得到一串零後,就像-23.0000000。我試圖通過更改爲@「%2f」來限制小數位數,但我不想爲整數整數或額外舍入兩個以上的小數位數。我只是想要它採取像34.658939或23,並使其爲-34.658939或-23。有沒有人有辦法做到這一點?

+0

這個問題涉及的花車格式:[更正浮點數(http://stackoverflow.com/questions/10049533/correcting-floating-point-numbers) – lnafziger

回答

1

什麼工作最好在你的情況是下面的代碼:

float input = [userinput.text floatValue]; 
float result = ((input * (-1))); 
NSNumber *resultNum = [NSNumber numberWithFloat:result]; 
NSString *resultString = [resultObj stringValue]; 
userinput.text = resultString; 

如果你想使負號,而不是反轉的標誌,它會更好,如果你有float result = -ABS(input);替換float result = ((input * (-1)));

+0

非常感謝這兩個答案真的有幫助,我能夠讓它正常工作! – user1123878

1

真的,處理這個問題的最好方法是永遠不要將它從字符串轉換爲首位。根據需要,這樣只需更換的第一個字符:

- (IBAction) negsign 
{ 
    unichar firstCharacter = [userinput.text characterAtIndex:0]; 
    if (firstCharacter == '-') { 
     // Change the first character to a + sign. 
     userinput.text = [userinput.text stringByReplacingCharactersInRange:NSMakeRange(0, 1) 
                   withString:@"+"]; 
    } else if (firstCharacter == '+') { 
     // Change the first character to a - sign. 
     userinput.text = [userinput.text stringByReplacingCharactersInRange:NSMakeRange(0, 1) 
                   withString:@"-"]; 
    } else { 
     // There is no sign so we assume that it is positive. 
     // Insert the - at the beginning. 
     userinput.text = [userinput.text stringByReplacingCharactersInRange:NSMakeRange(0, 0) 
                   withString:@"-"]; 
    } 
}