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

前端 未结 11 1845
粉色の甜心
粉色の甜心 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: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.

提交回复
热议问题