简体   繁体   中英

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];

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM