NSString 就像 "1000.00" 和 "1008977.72",
如何将它们格式化为“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
刚刚用 Swift 翻译:
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"