Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSNumberFormatter currency remove trailing zeros

I want to format prices like 45.50 but I don't want prices like 45.00. How can I avoid this?

like image 238
efpies Avatar asked Dec 04 '25 12:12

efpies


1 Answers

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

like image 65
surfrider Avatar answered Dec 06 '25 05:12

surfrider



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!