I want to format prices like 45.50 but I don't want prices like 45.00. How can I avoid this?
I did it this way:
NSNumber *amount = @(50.5);
NSNumberFormatter *currencyFormat = [[NSNumberFormatter alloc] init];
[currencyFormat setNumberStyle:NSNumberFormatterCurrencyStyle];
[currencyFormat setLocale:[NSLocale currentLocale]];
if (trunc(amount.floatValue) == amount.floatValue) {
[currencyFormat setMaximumFractionDigits:0];
} else {
[currencyFormat setMaximumFractionDigits:2];
}
NSLog(@"%@", [currencyFormat stringFromNumber:amount]);
I like this solution for its simplicity. Output will be $50.50. And for amount = @(50.0) will be $50
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With