iOS开发 ☞ 数字格式化NSNumberFormatter

一、NSString与NSNumber的相互转化

//末尾的零会被舍去
- (nullable NSString *)stringFromNumber:(NSNumber *)number;
- (nullable NSNumber *)numberFromString:(NSString *)string;

可以通过设置NSNumberFormatter的numberStyle来控制转为字符串的格式

@property NSNumberFormatterStyle numberStyle;

它是一个枚举值

typedef NS_ENUM(NSUInteger, NSNumberFormatterStyle) { NSNumberFormatterNoStyle = kCFNumberFormatterNoStyle, NSNumberFormatterDecimalStyle = kCFNumberFormatterDecimalStyle, NSNumberFormatterCurrencyStyle = kCFNumberFormatterCurrencyStyle, NSNumberFormatterPercentStyle = kCFNumberFormatterPercentStyle, NSNumberFormatterScientificStyle = kCFNumberFormatterScientificStyle, NSNumberFormatterSpellOutStyle = kCFNumberFormatterSpellOutStyle, NSNumberFormatterOrdinalStyle NS_ENUM_AVAILABLE(10_11, 9_0) = kCFNumberFormatterOrdinalStyle, NSNumberFormatterCurrencyISOCodeStyle NS_ENUM_AVAILABLE(10_11, 9_0) = kCFNumberFormatterCurrencyISOCodeStyle, NSNumberFormatterCurrencyPluralStyle NS_ENUM_AVAILABLE(10_11, 9_0) = kCFNumberFormatterCurrencyPluralStyle, NSNumberFormatterCurrencyAccountingStyle NS_ENUM_AVAILABLE(10_11, 9_0) = kCFNumberFormatterCurrencyAccountingStyle, };

1、NSNumberFormatterDecimalStyle = kCFNumberFormatterDecimalStyle
特点:
1、保留三位小数
2、若小数点后面第三位是零,则看第四位,6及6以上进位,6以下不进位并且舍去零位。
3、若小数点后面第三位不为零,则第四位四舍五入进位。

NSNumberFormatter *f = [[NSNumberFormatter alloc] init];
    f.numberStyle = NSNumberFormatterDecimalStyle;
    NSString *log = [f stringFromNumber:@111111111];
    //111,111,111
    NSLog(@"%@",log);

2、NSNumberFormatterRoundCeiling 小数部分四舍五入(只看小数点后面第一位)

二、自定义格式

看一来自stackOverFlow的例子

NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setPositiveFormat:@"00.00E+00"];
NSNumber *number = [NSNumber numberWithFloat:121212.12];
NSString *convertNumber = [formatter stringFromNumber:number];

你可能感兴趣的:(格式化,NSString)