通过NSNumberFormatter,可以设置NSNumber输出的格式。例如如下代码:
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.numberStyle = NSNumberFormatterDecimalStyle;
NSString *string = [formatter stringFromNumber:[NSNumber numberWithInt:123456789]];
NSLog(@"Formatted number string:%@",string);
输出结果为:[1223:403] Formatted number string:123,456,789
其中NSNumberFormatter类有个属性numberStyle,它是一个枚举型,设置不同的值可以输出不同的数字格式。该枚举包括:
enum {
NSNumberFormatterNoStyle = kCFNumberFormatterNoStyle,
NSNumberFormatterDecimalStyle = kCFNumberFormatterDecimalStyle,
NSNumberFormatterCurrencyStyle = kCFNumberFormatterCurrencyStyle,
NSNumberFormatterPercentStyle = kCFNumberFormatterPercentStyle,
NSNumberFormatterScientificStyle = kCFNumberFormatterScientificStyle,
NSNumberFormatterSpellOutStyle = kCFNumberFormatterSpellOutStyle
NSNumberFormatterRoundCeiling = kCFNumberFormatterRoundCeiling,//四舍五入,原值2.7999999999,直接输出3
NSNumberFormatterRoundFloor = kCFNumberFormatterRoundFloor,//保留小数输出2.8 正是想要的
NSNumberFormatterRoundDown = kCFNumberFormatterRoundDown,//加上了人民币标志,原值输出¥2.8
NSNumberFormatterRoundUp = kCFNumberFormatterRoundUp,//本身数值乘以100后用百分号表示,输出280%
NSNumberFormatterRoundHalfEven = kCFNumberFormatterRoundHalfEven,//原值表示,输出2.799999999E0
NSNumberFormatterRoundHalfDown = kCFNumberFormatterRoundHalfDown,//原值的中文表示,输出二点七九九九。。。。
NSNumberFormatterRoundHalfUp = kCFNumberFormatterRoundHalfUp //原值中文表示,输出第三
};
typedef NSUInteger NSNumberFormatterStyle;
各个枚举对应输出数字格式的效果如下:
[1243:403] Formatted number string:123456789
[1243:403] Formatted number string:123,456,789
[1243:403] Formatted number string:¥123,456,789.00
[1243:403] Formatted number string:-539,222,988%
[1243:403] Formatted number string:1.23456789E8
[1243:403] Formatted number string:一亿二千三百四十五万六千七百八十九
其中第三项和最后一项的输出会根据系统设置的语言区域的不同而不同
网友评论