Fork me on GitHub

iOS中的数字字符串格式化

由于项目中需要将数字转为货币格式:¥123,456,789.00,幸好iOS中有专门处理数字转字符串时格式化的函数。

在iOS中我们可以通过NSDateFormatter来设置输出NSDate的格式。相比NSDateFormatter的大名鼎鼎,NSNumberFormatter好像知道的人就不多了。其实通过NSNumberFormatter,同样可以设置NSNumber输出的格式。例如如下代码:

1
2
3
4
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];  
formatter.numberStyle = NSNumberFormatterDecimalStyle;
NSString *string = [formatter stringFromNumber:[NSNumber numberWithInt:123456789]];
NSLog(@"Formatted number string:%@", string);

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

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

1
2
3
4
5
6
7
8
typedef NS_ENUM(NSUInteger, NSNumberFormatterStyle) {
NSNumberFormatterNoStyle = kCFNumberFormatterNoStyle,
NSNumberFormatterDecimalStyle = kCFNumberFormatterDecimalStyle,
NSNumberFormatterCurrencyStyle = kCFNumberFormatterCurrencyStyle,
NSNumberFormatterPercentStyle = kCFNumberFormatterPercentStyle,
NSNumberFormatterScientificStyle = kCFNumberFormatterScientificStyle,
NSNumberFormatterSpellOutStyle = kCFNumberFormatterSpellOutStyle,
};

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

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

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

另外介绍一些不常见的数字转字符串的用法:

1,下面是一个浮点类型的数字转成String字符串的例子
Swift:

1
2
3
var f = 123.32342342
var s = "\(f)" // 123.32342342
var s1 = String(f) // 123.32342342

Objective-C:

1
2
float f = 123.32342342;
NSString *s = [NSString stringWithFormat:@"%f", f]; // 123.32342342

2,如果要保留两位小数
Swift:

1
2
var f = 123.32342342
var s = String(format: "%.2f", f) // 123.32

Objective-C:

1
2
float f = 123.32342342;
NSString *s = [NSString stringWithFormat:@"%.2f", f]; // 123.32

3,转成十六进制格式字符串
Swift:

1
2
let i = 255
let s = String(format: "%x", i) // ff

Objective-C:

1
2
int i = 255;
NSString *s = [NSString stringWithFormat:@"%x", f]; // ff

4,不足六位前面补0
Swift:

1
2
let i = 255
let s = String(format: "%06d", i) // 000255

Objective-C:

1
2
int i = 255;
NSString *s = [NSString stringWithFormat:@"%06d", i]; // 000255

------------- 本文结束感谢您的阅读 -------------