NSNumber 转 NSString

之前number 转string时候调用stringValue,后来发现未完全转

NSNumber * a_num = [NSNumber numberWithInteger: ];

NSString *value_str = [num stringValue];(不推荐)

官方推荐用这个方法, localizedStringFromNumber

NSString *num_str = [NSNumberFormatter localizedStringFromNumber:num numberStyle:NSNumberFormatterNoStyle];

通过NSNumberFormatter,可以设置NSNumber输出的格式。例如如下代码:

         NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];

         formatter.numberStyle = NSNumberFormatterDecimalStyle;

         NSString *string = [formatter stringFromNumber:[NSNumber numberWithInt:]];

         NSLog(@"Formatted number string:%@",string);

输出结果为:[1223:403] Formatted number string:123,456,789

其中NSNumberFormatter类有个属性numberStyle,它是一个枚举型,设置不同的值可以输出不同的数字格式。该枚举包括:

 enum {

     NSNumberFormatterNoStyle = kCFNumberFormatterNoStyle, //无格式

     NSNumberFormatterDecimalStyle = kCFNumberFormatterDecimalStyle, //小数型

     NSNumberFormatterCurrencyStyle = kCFNumberFormatterCurrencyStyle, //货币型

     NSNumberFormatterPercentStyle = kCFNumberFormatterPercentStyle,  //百分比型

     NSNumberFormatterScientificStyle = kCFNumberFormatterScientificStyle, //科学计数型

     NSNumberFormatterSpellOutStyle = kCFNumberFormatterSpellOutStyle  //全拼

 y    

     NSNumberFormatterRoundCeiling = kCFNumberFormatterRoundCeiling,//四舍五入,原值2.7999999999,直接输出3
NSNumberFormatterRoundFloor = kCFNumberFormatterRoundFloor,//保留小数输出2.8 正是想要的
NSNumberFormatterRoundDown = kCFNumberFormatterRoundDown,//加上了人民币标志,原值输出¥2.8
NSNumberFormatterRoundUp = kCFNumberFormatterRoundUp,//本身数值乘以100后用百分号表示,输出280%
NSNumberFormatterRoundHalfEven = kCFNumberFormatterRoundHalfEven,//原值表示,输出 NSNumberFormatterRoundHalfDown = kCFNumberFormatterRoundHalfDown,//原值的中文表示,输出二点七九九九。。。。
NSNumberFormatterRoundHalfUp = kCFNumberFormatterRoundHalfUp //原值中文表示,输出第三
}; typedef NSUInteger NSNumberFormatterStyle;

各个枚举对应输出数字格式的效果如下:

[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:一亿二千三百四十五万六千七百八十九

其中第三项和最后一项的输出会根据系统设置的语言区域的不同而不同

上一篇:Android通过webservice连接SQLServer 详细教程(数据库+服务器+客户端)


下一篇:Go语言中的互斥锁和读写锁(Mutex和RWMutex)