【问题标题】:How to set the textfield format as decimal while typing?输入时如何将文本字段格式设置为十进制?
【发布时间】:2011-09-16 07:12:44
【问题描述】:

在我的应用程序中,我有一个文本字段,当我单击该文本字段时,数字键盘将打开。现在我的问题是如何在键入时将该值转换为十进制格式,因为我必须在数字键盘中插入十进制值dot(.) 没有给出。所以当用户在文本字段中输入时,它会自动将该值转换为十进制格式。

假设如果用户输入 5078,它会在输入时显示 50.78 格式。

【问题讨论】:

  • 是固定的小数位,它将出现在某些数字之前或之后
  • 如果是 5 或 50 或 5000078 会发生什么。
  • 如果他只输入878 会怎样?
  • 小数点后两位是固定的。如果用户类型 5,它将显示 0.05,对于 5000078,它将显示 50000.78

标签: iphone objective-c xcode


【解决方案1】:

您可以简单地将数字乘以“0.01”(保留两位小数)并使用字符串格式“%.2lf”。在 textField:shouldChangeCharactersInRange:withString: 方法中编写以下代码。

NSString *text = [textField.text stringByReplacingCharactersInRange:range withString:string];
text = [text stringByReplacingOccurrencesOfString:@"." withString:@""];
double number = [text intValue] * 0.01;
textField.text = [NSString stringWithFormat:@"%.2lf", number];
return NO;

【讨论】:

    【解决方案2】:

    试试这个。

     -(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)
        {
            textField.text=@"";
            return YES;
        }
        return NO;
        }
    

    【讨论】:

    • 这样就解决了问题。但是你仍然可以通过简单的乘法和字符串格式来做到这一点!
    【解决方案3】:

    感谢用户,它对我来说很好用。我的情况是,我需要在完成编辑时像货币本地化格式一样格式化小数。

    - (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;
    

    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多