如何在NSString中使用千位分隔符

时间:2012-04-11 09:29:07

标签: ios nsstring

NSString就像“1000.00”和“1008977.72”,

如何将它们格式化为“1,000.00”和“1,008,977.00”

这是我的问题,请帮助我,提前谢谢你。

2 个答案:

答案 0 :(得分:47)

我做的不是很久。这是代码:

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

答案 1 :(得分:1)

刚刚翻译成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"