Is there a simple way to format currency into string in iOS?

前端 未结 7 1084

I need a way to format the price from NSNumber into a string like this: \"USD 0.99\", not \"$ 0.99\".

My game uses custom fonts, and they could not have the symbols

相关标签:
7条回答
  • 2020-12-23 16:04

    SKProduct price is a NSDecimalNumber object, so one way you could do this would be to extend the NSDecimalNumber class. Here's my Swift code for this:

    extension NSDecimalNumber {
        func asCurrency(locale:NSLocale) -> String? {
            var numberFormatter = NSNumberFormatter()
            numberFormatter.formatterBehavior = NSNumberFormatterBehavior.Behavior10_4
            numberFormatter.numberStyle = NSNumberFormatterStyle.CurrencyStyle
            numberFormatter.locale = locale
            return numberFormatter.stringFromNumber(self)
        }
    }
    

    in Objective-C it would look like this:

    @interface NSDecimalNumber (CurrencyExtension)
    
    - (NSString*) asCurrency: (NSLocale *)locale;
    
    @end
    
    @implementation NSDecimalNumber (DellExtensions)
    
    - (NSString*) asCurrency: (NSLocale *)locale {
        NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
        [numberFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
        [numberFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
        [numberFormatter setLocale:product.priceLocale];
        return [numberFormatter stringFromNumber:product.price];
    }
    
    @end
    
    0 讨论(0)
提交回复
热议问题