根据货币样式格式化文本字段

时间:2016-12-15 11:07:54

标签: ios objective-c

如何通过分隔由逗号输入的数字来格式化UITextfield,基于10,000,000这样的面额。

2 个答案:

答案 0 :(得分:0)

首先使用十进制样式创建数字格式化程序对象,然后将数字转换为格式化字符串

    NSNumberFormatter *formatter = [NSNumberFormatter new];
    [formatter setNumberStyle:NSNumberFormatterDecimalStyle];


    long priceInt =  10000000;


    NSString *formatted = [formatter stringFromNumber:[NSNumber numberWithLong:priceInt]];

答案 1 :(得分:0)

@interface NSString (NumberPadTools)

- (NSString*)numberPadformattedString;

@end


@implementation NSString (NumberPadTools)

- (NSString*)numberPadformattedString {
    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    [formatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
    [formatter setNumberStyle:NSNumberFormatterDecimalStyle];
    formatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
    [formatter setGroupingSeparator:@","];
    [formatter setDecimalSeparator:@"."];
    [formatter setMaximumFractionDigits:12];
    // Decimal values read from any db are always written with no grouping separator and a comma for decimal.

    NSNumber *numberFromString = [formatter numberFromString:self];

    [formatter setGroupingSeparator:@","]; // Whatever you want here
    [formatter setDecimalSeparator:@"."]; // Whatever you want here

    NSString *finalValue = [formatter stringFromNumber:numberFromString];
    return finalValue;
}

@end