Easiest way to format a number with thousand separators to an NSString according to the Locale

后端 未结 5 1425
悲&欢浪女
悲&欢浪女 2020-12-09 02:45

I can\'t seem to find an easy way to do it. The exact thing I need is:

[NSString stringWithFormat:@\"%d doodads\", n];

Where n is an int. S

5条回答
  •  我在风中等你
    2020-12-09 03:16

    I have recently discovered this one-liner:

    [@1234567 descriptionWithLocale:[NSLocale currentLocale]];  // 1,234,567
    

    Or in Swift 2:

    1234567.descriptionWithLocale(NSLocale.currentLocale())     // 1,234,567
    

    Swift 3/4:

    (1234567 as NSNumber).description(withLocale: Locale.current)
    

    Formatted per the question:

    [@(n) descriptionWithLocale:[NSLocale currentLocale]];
    

    Formatted without Objective-C literals:

    [[NSNumber numberWithInt:n] descriptionWithLocale:[NSLocale currentLocale]];
    

    This is the solution I was looking for when I asked the question. Available since iOS 2.0 and OS X 10.0, documented to return a string version of the number formatted as per the locale provided. stringValue is even documented to use this method but passing nil.

    Seeing as it is my question and this fits my answer best, I am tempted to change the tick, but it seems cruel. Update I changed the tick, this answer is the answer.

提交回复
热议问题