How to properly format currency on ios

后端 未结 7 1102
梦谈多话
梦谈多话 2020-12-01 09:19

I\'m looking for a way to format a string into currency without using the TextField hack.

For example, i\'d like to have the number \"521242\" converted into \"5,212

7条回答
  •  时光取名叫无心
    2020-12-01 09:36

    I use this code. This work for me

    1) Add UITextField Delegate to header file

    2) Add this code (ARC enabled)

    - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    
    NSString *cleanCentString = [[textField.text
                                  componentsSeparatedByCharactersInSet:
                                  [[NSCharacterSet decimalDigitCharacterSet] invertedSet]]
                                 componentsJoinedByString:@""];
    // Parse final integer value
    NSInteger centAmount = cleanCentString.integerValue;
    // Check the user input
    if (string.length > 0)
    {
        // Digit added
        centAmount = centAmount * 10 + string.integerValue;
    }
    else
    {
        // Digit deleted
        centAmount = centAmount / 10;
    }
    // Update call amount value
    NSNumber *amount = [[NSNumber alloc] initWithFloat:(float)centAmount / 100.0f];
    // Write amount with currency symbols to the textfield
    NSNumberFormatter *_currencyFormatter = [[NSNumberFormatter alloc] init];
    [_currencyFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
    [_currencyFormatter setCurrencyCode:@"USD"];
    [_currencyFormatter setNegativeFormat:@"-¤#,##0.00"];
    textField.text = [_currencyFormatter stringFromNumber:amount];
    return NO; }
    

提交回复
热议问题