在我的應用程序中,我有一個文本字段,當我點擊該文本字段時,數字鍵盤將打開。現在我的問題是如何在打字時將該值轉換爲十進制格式,因爲我必須只插入十進制值並在數字鍵盤中點(。)沒有給出,所以當用戶輸入文本字段時,它會自動將該值轉換爲十進制格式。如何在輸入時將文本字段格式設置爲小數?
想,如果用戶類型它會顯示50.78格式,而打字。
在我的應用程序中,我有一個文本字段,當我點擊該文本字段時,數字鍵盤將打開。現在我的問題是如何在打字時將該值轉換爲十進制格式,因爲我必須只插入十進制值並在數字鍵盤中點(。)沒有給出,所以當用戶輸入文本字段時,它會自動將該值轉換爲十進制格式。如何在輸入時將文本字段格式設置爲小數?
想,如果用戶類型它會顯示50.78格式,而打字。
您可以簡單地通過 「0.01」 乘數(小數點後兩位),並使用字符串格式 「%.2lf」。在textField:shouldChangeCharactersInRange:withString:
方法中寫下面的代碼。
謝謝你工作正常。 – Developer
歡迎您! – EmptyStack
試試這個。
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range
replacementString:(NSString *)string {
double currentValue = [textField.text doubleValue];
double cents = round(currentValue * 100.0f);
if ([string length]) {
for (size_t i = 0; i < [string length]; i++) {
unichar c = [string characterAtIndex:i];
if (isnumber(c)) {
cents *= 10;
cents += c - '0';
}
}
} else {
// back Space
cents = floor(cents/10);
}
textField.text = [NSString stringWithFormat:@"%.2f", cents/100.0f];
if(cents==0)
{
[email protected]"";
return YES;
}
return NO;
}
這就解決了這個問題。但是你仍然可以通過簡單的乘法和字符串格式來實現! – EmptyStack
是的...但這是另一種選擇.... – userar
謝謝使用者,它適用於我。林我的情況下,我需要格式化小數點後,像完成編輯時的貨幣本地化格式。
- (BOOL) textFieldShouldEndEditing:(UITextField *)textField {
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.numberStyle = NSNumberFormatterCurrencyStyle;
// im my case i need specify the currency code,
// but could have got it from the system.
formatter.currencyCode = @"BRL";
NSDecimalNumber *decimalNumber =
[NSDecimalNumber decimalNumberWithString:textField.text];
// keeping the decimal value for submit to server.
self.decimalValue = decimalNumber;
// formatting to currency string.
NSString * currencyString = [formatter stringFromNumber:decimalNumber];
textField.text = currencyString;
}
是小數點位置固定,這將一些數字 – Gypsa
之前或之後來,如果是5或50或5000078將hapeen什麼。 – Gypsa
如果他只是輸入'8'或'78',該怎麼辦? – EmptyStack