常用NSDateFormatter,但少见NSNumberFormatter ,但后者似乎功能更丰富,也更实用。
类方法
/*
eg. 12345.345
NSNumberFormatterNoStyle //四舍五入整数
NSNumberFormatterDecimalStyle //小数形式
NSNumberFormatterCurrencyStyle //本地货币样式,保留两位小数 $12,345.34
NSNumberFormatterPercentStyle //百分比样式 1,234,534%
NSNumberFormatterScientificStyle //科学计数样式 1.2345345E4
NSNumberFormatterSpellOutStyle //朗读样式 twelve thousand three hundred forty-five point three four five
iOS 9.0后
NSNumberFormatterOrdinalStyle //序数样式 12,345th
NSNumberFormatterCurrencyISOCodeStyle //货币代码样式 USD12,345.34
NSNumberFormatterCurrencyPluralStyle //本地货币样式 12,345.34 US dollars
NSNumberFormatterCurrencyAccountingStyle //会计计数 $12,345.34
*/
NSNumber *number = [NSNumber numberWithDouble:12345.345];
NSString *numberNoStyleStr = [NSNumberFormatter localizedStringFromNumber:number numberStyle:NSNumberFormatterCurrencyAccountingStyle];
实例方法
//实例方法
NSNumberFormatter *formatter = [[NSNumberFormatter alloc]init];
//舍入值
formatter.roundingIncrement = @10;
formatter.roundingMode = kCFNumberFormatterRoundUp;
NSLog(@"%@",[formatter numberFromString:@""]);
//样式
formatter.numberStyle = NSNumberFormatterDecimalStyle ;
//宽度,包括前后缀在内的宽度
formatter.formatWidth = 12;
//填充位置符(单个字符)
formatter.paddingCharacter = @"X";
formatter.paddingPosition = NSNumberFormatterDecimalStyle;
/*
NSNumberFormatterPadBeforePrefix
NSNumberFormatterPadAfterPrefix
NSNumberFormatterPadBeforeSuffix
NSNumberFormatterPadAfterSuffix
*/
//后缀
formatter.positiveSuffix = @"元";
//前缀
formatter.positivePrefix = @"¥";
//缩放因子
formatter.multiplier = @10;
//负数样式
formatter.negativeFormat = @"-";
//正数样式
formatter.positiveFormat = @"+";
//小数点的样式
formatter.decimalSeparator = @".";
//零的样式
formatter.zeroSymbol = @"0";
//设置了这个后,会自动用0补充而不用位置符
//整数的最多/少位数
formatter.maximumIntegerDigits = 100;
formatter.minimumIntegerDigits = 10;
//小数的最多/少位数
formatter.maximumFractionDigits = 10;
formatter.minimumFractionDigits = 7;
NSLog(@"%@",[formatter stringFromNumber:number]);