Objective-C: How to format string as $ Price

前端 未结 4 1875
忘了有多久
忘了有多久 2020-12-05 23:42

Is their a built-in way of formatting string as $ price, e.g. 12345.45 converted to $12,345.45?

相关标签:
4条回答
  • 2020-12-05 23:46

    Assuming the price is held in a float, you probably want +localizedStringWithFormat:.

    NSString *priceString = [NSString localizedStringWithFormat:@"$ %'.2f",price];
    

    Hmmm... Apple says they follow the IEEE standard for printf, so it should accept the ' flag, but it doesn't work on Tiger. NSNumberFormatter it is.

    0 讨论(0)
  • 2020-12-06 00:00

    You need to get rid of the ' character

    So, just have this:

    NSString *priceString = [NSString localizedStringWithFormat:@"$ %.2f", price];
    
    0 讨论(0)
  • 2020-12-06 00:09

    Assuming you are using Cocoa (or just Foundation), you can use NSNumberFormatter and set its style to currency:

    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    [formatter setNumberStyle:NSNumberFormatterCurrencyStyle];
    ... = [formatter stringFromNumber:number];
    

    By default it uses the locale of your system, but you can change that and lots of other properties, see the NSNumberFormatter API docs.

    0 讨论(0)
  • 2020-12-06 00:10
    NSString *formatedNumbers = [NSNumberFormatter localizedStringFromNumber:myNumber numberStyle:NSNumberFormatterCurrencyStyle];
    
    0 讨论(0)
提交回复
热议问题