NSNumberFormatter是iOS数字格式化的一个类
NSNumberFormatter * formatter = [[NSNumberFormatter alloc] init];
formatter.numberStyle = NSNumberFormatterDecimalStyle;
NSNumber * number = @(98764.12345);
NSString * string = [formatter stringFromNumber:number];
设置不同的numberStyle获得的结果各不相同
NSNumberFormatterNoStyle = 98764
NSNumberFormatterCurrencyStyle = US$98,764.12
NSNumberFormatterDecimalStyle = 98,764.123
NSNumberFormatterPercentStyle = 9,876,412%
NSNumberFormatterScientificStyle = 9.876412345E4
NSNumberFormatterSpellOutStyle = 九万八千七百六十四点一二三四五
NSNumberFormatterOrdinalStyle = 第9,8764
NSNumberFormatterCurrencyISOCodeStyle = USD98,764.12end
NSNumberFormatterCurrencyPluralStyle = 98,764.12美元
NSNumberFormatterCurrencyAccountingStyle = US$98,764.12
设置小数位数
formatter.maximumFractionDigits = 3; //设置最大小数点后的位数
formatter.minimumFractionDigits = 2; //设置最小小数点后的位数
roundingMode 设置是否四舍五入 修改number的值为
number = @(98764.12545);
以下是设置roundingMode保留2为小数的结果
NSNumberFormatterRoundFloor = 98,764.12 //不四舍五入
NSNumberFormatterRoundCeiling = 98,764.13 //四舍五入
NSNumberFormatterRoundDown = 98,764.12 //只舍不入
number = @(98764.12145); //修改number的值
NSNumberFormatterRoundUp = 98,764.13 //只入不舍
number = [NSNumber numberWithFloat:98764.13645];
NSNumberFormatterRoundHalfEven = 98,764.13
NSNumberFormatterRoundHalfDown = 98,764.13
NSNumberFormatterRoundHalfUp = 98,764.13
number = [NSNumber numberWithDouble:98764.13645];
NSNumberFormatterRoundHalfEven = 98,764.14
NSNumberFormatterRoundHalfDown = 98,764.14
NSNumberFormatterRoundHalfUp = 98,764.14
最后NSNumberFormatter还可以自定义数据格式
[formatter setPositiveFormat:@"#,###.##"]; //自定义数据格式
//98,764.14
[formatter setPositiveFormat:@"#,####.##"]; //自定义数据格式
//9,8764.14