Search code examples
iosobjective-capplet

Currency sign label showing the wrong value using Objective-C


The currency label is meant to display "£" if the currency value is equal to GBP and if not, display the "€"sign. However, it's returning the "$" sign no matter if the currency is GBP or EURO. Why?

NSString *currencySign = [overviewModel.currency isEqualToString:@"GBP"] ? @"£" : @"€";
self.productCoreDetailView.priceLabel.text = [NSString stringWithFormat:@"%@%@", currencySign, overviewModel.price];
self.productCoreDetailView.priceVATLabel.text = [NSString stringWithFormat:@"%@%@", currencySign, overviewModel.price_vat];

Solution

  • Instead of doing this manually, why not use the NSNumberFormatter instead?

    NSNumberFormatter *formatter = [NSNumberFormatter new];
    formatter.numberStyle = NSNumberFormatterCurrencyStyle;
    formatter.currencyCode = @"GBP";
    NSString *formattedNumber = [formatter stringFromNumber:@23.50];
    // formattedNumber = £23.50
    

    Or Swift

    let formatter = NumberFormatter()
    formatter.numberStyle = .currency
    formatter.currencyCode = "EUR"
    let formattedNumber = formatter.string(from: 23.50)
    // formattedNumber = €23.50
    

    By using NSNumberFormatter you will be able to support any currency and simplify your code.