根据Locale,使用千位分隔符将数字格式化为NSString的最简单方法

mxc*_*xcl 26 cocoa string-formatting

我似乎找不到一个简单的方法来做到这一点.我需要的确切事项是:

[NSString stringWithFormat:@"%d doodads", n];
Run Code Online (Sandbox Code Playgroud)

其中n是int.因此对于1234我想要这个字符串(在我的语言环境下):

@"1,234 doodads"
Run Code Online (Sandbox Code Playgroud)

谢谢.

小智 51

对于10.6,这适用于:

NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setFormatterBehavior: NSNumberFormatterBehavior10_4];
[numberFormatter setNumberStyle: NSNumberFormatterDecimalStyle];
NSString *numberString = [numberFormatter stringFromNumber: [NSNumber numberWithInteger: i]];
Run Code Online (Sandbox Code Playgroud)

它正确处理本地化.


mxc*_*xcl 28

我最近发现了这个单行:

[@1234567 descriptionWithLocale:[NSLocale currentLocale]];  // 1,234,567
Run Code Online (Sandbox Code Playgroud)

或者在Swift 2中:

1234567.descriptionWithLocale(NSLocale.currentLocale())     // 1,234,567
Run Code Online (Sandbox Code Playgroud)

迅捷3/4:

(1234567 as NSNumber).description(withLocale: Locale.current)
Run Code Online (Sandbox Code Playgroud)

根据问题格式化:

[@(n) descriptionWithLocale:[NSLocale currentLocale]];
Run Code Online (Sandbox Code Playgroud)

没有Objective-C文字格式化:

[[NSNumber numberWithInt:n] descriptionWithLocale:[NSLocale currentLocale]];
Run Code Online (Sandbox Code Playgroud)

当我问这个问题时,这是我正在寻找的解决方案.从iOS 2.0和OS X 10.0开始提供,记录为返回根据提供的语言环境格式化的数字的字符串版本.stringValue甚至记录了使用这种方法但传递nil.

看到这是我的问题,这最适合我的答案,我很想改变勾号,但似乎很残忍.更新我改变了蜱,这个答案答案.


ban*_*isa 26

下面没有解决语言环境,但它是一种更好的方式(在我看来)在数字格式化器上设置千位分隔符.

NSNumberFormatter *numberFormat = [[[NSNumberFormatter alloc] init] autorelease];
numberFormat.usesGroupingSeparator = YES;
numberFormat.groupingSeparator = @",";
numberFormat.groupingSize = 3;   
Run Code Online (Sandbox Code Playgroud)

  • 很好,如果它有效,但这是严格的英文格式,而不是机器的默认语言环境。 (2认同)
  • 但您明确将分组分隔符设置为逗号。许多语言环境并非如此。此外,并非所有区域设置中的分组大小都为 3。 (2认同)