NSNumberFormatter是iOS數(shù)字格式化的一個(gè)類
NSNumberFormatter * formatter = [[NSNumberFormatter alloc] init];
formatter.numberStyle = NSNumberFormatterDecimalStyle;
NSNumber * number = @(98764.12345);
NSString * string = [formatter stringFromNumber:number];
設(shè)置不同的numberStyle獲得的結(jié)果各不相同
NSNumberFormatterNoStyle = 98764
NSNumberFormatterCurrencyStyle = US$98,764.12
NSNumberFormatterDecimalStyle = 98,764.123
NSNumberFormatterPercentStyle = 9,876,412%
NSNumberFormatterScientificStyle = 9.876412345E4
NSNumberFormatterSpellOutStyle = 九萬八千七百六十四點(diǎn)一二三四五
NSNumberFormatterOrdinalStyle = 第9,8764
NSNumberFormatterCurrencyISOCodeStyle = USD98,764.12end
NSNumberFormatterCurrencyPluralStyle = 98,764.12美元
NSNumberFormatterCurrencyAccountingStyle = US$98,764.12
設(shè)置小數(shù)位數(shù)
formatter.maximumFractionDigits = 3; //設(shè)置最大小數(shù)點(diǎn)后的位數(shù)
formatter.minimumFractionDigits = 2; //設(shè)置最小小數(shù)點(diǎn)后的位數(shù)
roundingMode 設(shè)置是否四舍五入 修改number的值為
number = @(98764.12545);
以下是設(shè)置roundingMode保留2為小數(shù)的結(jié)果
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還可以自定義數(shù)據(jù)格式
[formatter setPositiveFormat:@"#,###.##"]; //自定義數(shù)據(jù)格式
//98,764.14
[formatter setPositiveFormat:@"#,####.##"]; //自定義數(shù)據(jù)格式
//9,8764.14