在开发的过程中,我们会遇到这样的问题,在金额没三位中间会加一个逗号的那种格式。例如:123456变成123,456的情况。
数字的格式化的代码:
NSString *numString = [NSString stringWithFormat:@"%@",@"12345678.89"];
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
NSNumber *number = [formatter numberFromString:numString];
formatter.numberStyle = kCFNumberFormatterDecimalStyle;
NSString *string = [formatter stringFromNumber:number];
NSLog(@"numberFormatter == %@",string);
格式化的类型有:
typedef CF_ENUM(CFIndex, CFNumberFormatterStyle) { // number format styles
kCFNumberFormatterNoStyle = 0,
kCFNumberFormatterDecimalStyle = 1,
kCFNumberFormatterCurrencyStyle = 2,
kCFNumberFormatterPercentStyle = 3,
kCFNumberFormatterScientificStyle = 4,
kCFNumberFormatterSpellOutStyle = 5,
kCFNumberFormatterOrdinalStyle CF_ENUM_AVAILABLE(10_11, 9_0) = 6,
kCFNumberFormatterCurrencyISOCodeStyle CF_ENUM_AVAILABLE(10_11, 9_0) = 8,
kCFNumberFormatterCurrencyPluralStyle CF_ENUM_AVAILABLE(10_11, 9_0) = 9,
kCFNumberFormatterCurrencyAccountingStyle CF_ENUM_AVAILABLE(10_11, 9_0) = 10,
};
对应的输出形式(英文环境):
numberFormatter == 12,345,678.89
numberFormatter == 12,345,678.89
numberFormatter == $12,345,678.89
numberFormatter == 1,234,567,889%
numberFormatter == 1.234567889E7
numberFormatter == twelve million three hundred forty-five thousand six hundred seventy-eight point eight nine
numberFormatter == 12,345,679th
numberFormatter == 3,429:21:19
numberFormatter == USD12,345,678.89
numberFormatter == 12,345,678.89 US dollars
对应的中文输出环境:
numberFormatter == 12,345,678.89
numberFormatter == 12,345,678.89
numberFormatter == US$ 12,345,678.89
numberFormatter == 1,234,567,889%
numberFormatter == 1.234567889E7
numberFormatter == 一千二百三十四万五千六百七十八点八九
numberFormatter == 第1234,5679
numberFormatter == 12,345,679
numberFormatter == USD 12,345,678.89
numberFormatter == 12,345,678.89美元