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

前端 未结 7 1089

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 15:48

    If you want it localized (ie the currency on the correct side of the price) it is a bit of a hassle.

    NSDecimalNumber *price = [NSDecimalNumber decimalNumberWithString:@"1.99"];
    NSLocale *priceLocale = [[[NSLocale alloc] initWithLocaleIdentifier:@"de_DE"] autorelease]; // get the locale from your SKProduct
    
    NSNumberFormatter *currencyFormatter = [[[NSNumberFormatter alloc] init] autorelease];
    [currencyFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
    [currencyFormatter setLocale:priceLocale];
    NSString *currencyString = [currencyFormatter internationalCurrencySymbol]; // EUR, GBP, USD...
    NSString *format = [currencyFormatter positiveFormat];
    format = [format stringByReplacingOccurrencesOfString:@"¤" withString:currencyString];
        // ¤ is a placeholder for the currency symbol
    [currencyFormatter setPositiveFormat:format];
    
    NSString *formattedCurrency = [currencyFormatter stringFromNumber:price];
    

    You have to use the locale you get from the SKProduct. Don't use [NSLocale currentLocale]!

提交回复
热议问题