Question

My app has calling credit. When it has ran out, the value final value is sometimes a little below 0 (e.g. -0.003). My code:

NSString*           formattedString;
NSNumberFormatter*  numberFormatter;

numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
[numberFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
[numberFormatter setLocale:((SKProduct*)self.products[0]).priceLocale];

formattedString = [numberFormatter stringFromNumber:@(price)];

then yields: -0.00. This looks weird on the UI. How can I correctly round so it will show 0.00 when it goes below zero?

Then, I'm looking for something generic enough that can handle price formats with varying number of fractional digits, and leaves visibly negative values (e.g. -0.02) untouched.

Was it helpful?

Solution 2

I ended up with:

...

double factor = pow(10, numberFormatter.maximumFractionDigits);
price = round(price * factor) / factor;
if (fpclassify(price) == FP_ZERO)
{
    price = fabs(price);
}

formattedString = [numberFormatter stringFromNumber:@(price)];

But I wonder if there's not a nicer/cleaner solution.

OTHER TIPS

There may be something you can configure on the number formatter, but if there isn't, you can do something like this:

if (fpclassify(price) == FP_ZERO)
{
    price = fabs(price);
}
formattedString = [numberFormatter stringFromNumber:@(price)];

This isn't clean, but it should be reliable.

formattedString = [numberFormatter stringFromNumber:@(price)];
NSLog(@"Before correction %@", formattedString);

if ([[numberFormatter numberFromString:formattedString] floatValue] == -0.0) {
    formattedString = [numberFormatter stringFromNumber:@0.0];
};
NSLog(@"After correction %@", formattedString);

This results in:

2014-04-16 15:00:05.887 APP_NAME[32121:60b] Before correction $-0.00
2014-04-16 15:00:05.890 APP_NAME[32121:60b] After correction $0.00
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top