Format currency in a Uitextfield

Asked

Viewed 1,447 times

3

I need to create a Uitextfield to add money values. But I need the user to see the value being added to Uitextfield in the order the user type. Example: User type 1 - Uitextfield appears 0.01 User type 5 - Uitextfield appears 0.15 User type 0 - Uitextfield appears 1.50

There enters my problem, when the user type the 4th digit, in my case this appearing 1,5,00 and not 15,00 as wish.

Follow the formatting code:

    NSNumberFormatter *valueTextFieldFormatter= [NSNumberFormatter new];
    [valueTextFieldFormatter setPositiveFormat:@"#0,0"];
    [valueTextFieldFormatter setNumberStyle:NSNumberFormatterDecimalStyle];

    NSString *num = [textField.text stringByReplacingOccurrencesOfString:@"," withString:@""];

    textField.text = [valueTextFieldFormatter stringFromNumber:[NSNumber numberWithInt:[num floatValue]]];

inserir a descrição da imagem aqui

  • The code I reported is within the method shouldChangeCharactersInRange

4 answers

6

David, there are simpler ways to solve this problem. Try changing the style of the number to Nsnumberformattercurrencystyle and putting a location as a reference for formatting.

NSNumberFormatter *n = [[NSNumberFormatter alloc] init];
[n setNumberStyle:NSNumberFormatterCurrencyStyle];
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"pt_BR"];
[n setLocale:locale];
NSString *saída = [n stringFromNumber:[NSNumber numberWithFloat:125.98]];

The exit will be $ 125,98.

  • Dude, in your example we have the full number already. In my case the number is forming as the user is typing. I didn’t have time to stir today, but the little test was like:1 R$0,001... 2 R$1,002.. 3 R$1,005,003

  • Rafael, if I don’t do the setLocale, he takes the locale of the region where the device is? Or uses the American default?

  • If the locale is not configured then what is set in the settings of the device will be used.

3

I have something a little different on shouldChangeCharactersInRange in an application of mine working the way you want.

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if ([textField tag] == 1) { // Só para identificar o campo de moeda
        NSString *replaced = [textField.text stringByReplacingCharactersInRange:range withString:string];
        NSDecimalNumber *amount = (NSDecimalNumber*) [self.formatter numberFromString:replaced];
        if (amount == nil) {
            return NO;
        }
        short powerOf10 = 0;
        if ([textField.text isEqualToString:@""]) {
            powerOf10 = -self.formatter.maximumFractionDigits;
        } else if (range.location + self.formatter.maximumFractionDigits >= textField.text.length) {
            if (range.length) {
                powerOf10 = -range.length;
            } else {
                powerOf10 = [string length];
            }
        }
        amount = [amount decimalNumberByMultiplyingByPowerOf10:powerOf10];
        textField.text = [self.formatter stringFromNumber:amount];
        return NO;
    }

    return YES;
}

And in the viewDidLoad: have my property formatter used above:

self.formatter = [NSNumberFormatter new];
[self.formatter setNumberStyle:NSNumberFormatterCurrencyStyle];
[self.formatter setLenient:YES];
[self.formatter setGeneratesDecimalNumbers:YES];
[self.formatter setCurrencySymbol:@""];
[self.formatter setInternationalCurrencySymbol:@""];

There is no need to locale, since it is already set in the settings of the device, unless you want some different.

  • Doubt, what are the commands for: setLenient, setCurrencySymbol and setInternationalCurrencySymbol? I tried to use mine and I saw no change...

2


I did a little different. This way I have the number informed by the user formatted on UITextField(valueTextField.text) and I have a version of it with just numbers(storeValue) in case you need to do math and stuff.

In the @interface:

   NSMutableString *storeValue;
   NSNumberFormatter *numberFormatter; 

In the viewDidLoad::

    storeValue = [NSMutableString new];
    numberFormatter = [NSNumberFormatter new];
    [numberFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
    [super viewDidLoad];

And in the shouldChangeCharactersInRange:

    if (textField == valueTextField) {
        if (string.length == 0) {
            int length = (storeValue.length - 1);
            if (length >= 0) {
                NSRange range = NSMakeRange(length, 1);
                [storeValue deleteCharactersInRange:range];
            };
        } else if ([textField.text length] <= 7) {
            [storeValue appendString:string];
        }

        NSString *newText = [numberFormatter stringFromNumber:[NSNumber numberWithFloat:([storeValue doubleValue] / 100)] ];
        [textField setText:[NSString stringWithFormat:@"%@",newText]];

        return NO;
    }

    return YES;

1

David Batista’s response was very helpful.

I’m writing the code on Swift and it worked really well.

if ((string as NSString).length == 0) {
        var length = (storeValue.length - 1);
        if (length >= 0) {
            var range = NSMakeRange(length, 1)

            storeValue.deleteCharactersInRange(range)
        }
    } else if ( (textField.text as NSString).length <= 15) {
        storeValue.appendString(string)
    }

    var newText = numberFormatter.stringFromNumber(NSNumber(double: storeValue.doubleValue/100))
    textField.text = NSString(format: "%@", newText!) as String

    return false

Browser other questions tagged

You are not signed in. Login or sign up in order to post.