通過(guò)NSNumberFormatter秩命,可以設(shè)置NSNumber輸出的格式实牡。例如如下代碼:
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.numberStyle = NSNumberFormatterDecimalStyle;
NSString *string = [formatter stringFromNumber:[NSNumber numberWithInt:123456789]];
NSLog(@"Formatted number string:%@",string);
輸出結(jié)果為:[1223:403] Formatted number string:123,456,789
其中NSNumberFormatter類有個(gè)屬性numberStyle,它是一個(gè)枚舉型,設(shè)置不同的值可以輸出不同的數(shù)字格式脸侥。該枚舉包括:
enum {
NSNumberFormatterNoStyle = kCFNumberFormatterNoStyle,
NSNumberFormatterDecimalStyle = kCFNumberFormatterDecimalStyle,
NSNumberFormatterCurrencyStyle = kCFNumberFormatterCurrencyStyle,
NSNumberFormatterPercentStyle = kCFNumberFormatterPercentStyle,
NSNumberFormatterScientificStyle = kCFNumberFormatterScientificStyle,
NSNumberFormatterSpellOutStyle = kCFNumberFormatterSpellOutStyle
NSNumberFormatterRoundCeiling = kCFNumberFormatterRoundCeiling,//四舍五入,原值2.7999999999,直接輸出3
NSNumberFormatterRoundFloor = kCFNumberFormatterRoundFloor,//保留小數(shù)輸出2.8 正是想要的
NSNumberFormatterRoundDown = kCFNumberFormatterRoundDown,//加上了人民幣標(biāo)志碌冶,原值輸出¥2.8
NSNumberFormatterRoundUp = kCFNumberFormatterRoundUp,//本身數(shù)值乘以100后用百分號(hào)表示,輸出280%
NSNumberFormatterRoundHalfEven = kCFNumberFormatterRoundHalfEven,//原值表示湿痢,輸出2.799999999E0
NSNumberFormatterRoundHalfDown = kCFNumberFormatterRoundHalfDown,//原值的中文表示,輸出二點(diǎn)七九九九扑庞。譬重。。罐氨。
NSNumberFormatterRoundHalfUp = kCFNumberFormatterRoundHalfUp //原值中文表示臀规,輸出第三
};
typedef NSUInteger NSNumberFormatterStyle;
各個(gè)枚舉對(duì)應(yīng)輸出數(shù)字格式的效果如下:
[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:一億二千三百四十五萬(wàn)六千七百八十九
其中第三項(xiàng)和最后一項(xiàng)的輸出會(huì)根據(jù)系統(tǒng)設(shè)置的語(yǔ)言區(qū)域的不同而不同