的NSString就像“1000.00”和“1008977.72”,如何使用千个分隔符在的NSString
我怎么能格式化为“1,000.00”和“1,008,977.00”
这是我的问题,并帮助我这个,先谢谢你。
的NSString就像“1000.00”和“1008977.72”,如何使用千个分隔符在的NSString
我怎么能格式化为“1,000.00”和“1,008,977.00”
这是我的问题,并帮助我这个,先谢谢你。
我做了那么长时间。下面的代码:
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setGroupingSeparator:@","];
[numberFormatter setGroupingSize:3];
[numberFormatter setUsesGroupingSeparator:YES];
[numberFormatter setDecimalSeparator:@"."];
[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
[numberFormatter setMaximumFractionDigits:2];
NSString *theString = [numberFormatter stringFromNumber:[NSNumber numberWithDouble:1008977.72]];
希望它可以帮助
编辑
由于Olie问我会后,将使用当前的区域设置来设置分组的编码/十进制分隔符本身。
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setLocale:[NSLocale currentLocale]];
[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
[numberFormatter setMaximumFractionDigits:2];
NSString *theString = [numberFormatter stringFromNumber:[NSNumber numberWithDouble:1008977.72]];
NSLog(@"The string: %@", theString);
使用[NSLocale localeWithLocaleIdentifier:]
代替[NSLocale currentLocale]
给我的结果如下:
[NSLocale localeWithLocaleIdentifier:@"be_NL"]
The string: 1 008 977,72
[NSLocale localeWithLocaleIdentifier:@"en_GB"]
The string: 1,008,977.72
[NSLocale localeWithLocaleIdentifier:@"DE"]
The string: 1.008.977,72
[NSLocale localeWithLocaleIdentifier:@"en_US"]
The string: 1,008,977.72
只是翻译斯威夫特:
let formatter = NumberFormatter()
formatter.groupingSeparator = ","
formatter.groupingSize = 3
formatter.usesGroupingSeparator = true
formatter.decimalSeparator = "."
formatter.numberStyle = .decimal
formatter.maximumFractionDigits = 2
formatter.minimumFractionDigits = 2
formatter.minimumIntegerDigits = 1
let result = formatter.string(from: NSNumber(value: value)) ?? "0.00"
这是相当不错的,但如果我上投你的答案您编辑以显示如何获取本地分组分隔符(* ie *,USA使用“,”,而大多数欧洲使用“。”作为千位分隔符,反之亦然,小数分隔符)。 – Olie 2015-03-23 22:23:15
@我希望我做对了。很长一段时间没有碰到任何Objective-C :-) – Novarg 2015-03-24 07:08:49
太棒了,谢谢! – Olie 2015-03-24 13:50:35