What is the best way to enter numeric values with decimal points?

前端 未结 11 1666
粉色の甜心
粉色の甜心 2020-11-27 11:25

In my app users need to be able to enter numeric values with decimal places. The iPhone doesn\'t provides a keyboard that\'s specific for this purpose - only a number pad an

相关标签:
11条回答
  • 2020-11-27 12:02

    Depending on the specific application, providing a slider that the user can select a position from might be a better choice on the iphone. Then no digits need to be entered at all.

    0 讨论(0)
  • 2020-11-27 12:09

    I built a custom Number pad view controller with decimal point... check it out:

    http://sites.google.com/site/psychopupnet/iphone-sdk/tenkeypadcustom10-keypadwithdecimal

    0 讨论(0)
  • 2020-11-27 12:13

    Here is an example for the solution suggested in the accepted answer. This doesn't handle other currencies or anything - in my case I only needed support for dollars, no matter what the locale/currency so this was OK for me:

    -(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range
        replacementString:(NSString *)string {
    
        double currentValue = [textField.text doubleValue];
        //Replace line above with this
        //double currentValue = [[textField text] substringFromIndex:1] 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];
        //Add this line
        //[textField setText:[NSString stringWithFormat:@"$%@",[textField text]]];
        return NO;
    }
    

    The rounds and floors are important a) because of the floating-point representation sometimes losing .00001 or whatever and b) the format string rounding up any precision we deleted in the backspace part.

    0 讨论(0)
  • 2020-11-27 12:13

    You may want to use a slider (as suggested by Martin v. Löwis) or a UIPickerView with a separate wheel for each of the digits.

    0 讨论(0)
  • 2020-11-27 12:13

    You can use STATextField and set currencyRepresentation to YES which:

    Ensures no more than one decimal point is entered and that no more than 2 digits are entered to the right of said decimal point.

    There's also STAATMTextField which supports currency mode and ATM text entry by default:

    Provides a text field that mimics ATM machine input behavior.

    0 讨论(0)
提交回复
热议问题