NSNumberFormatter rounding to negative zero

I use NSNumberFormatter to format float values ​​as whole strings, i.e. lowering the fractional part. I find it strange that numbers in the range (-0.5, 0) * open interval end with -0 . Since this value will be displayed to the user, I think a negative zero is not appropriate. I experimented with various combinations of numberStyle and roundingMode without success.

Is there a way to configure NSNumberFormatter to output them as 0 , or do I need to resort to manual correction for this range?

+6
source share
2 answers

I had to fix it myself. I use NSNumberFormatter to display the default temperature numberStyle - NSNumberFormatterNoStyle , which rounds the numbers to an integer, roundingMode set to NSNumberFormatterRoundHalfUp . In the end, I intercepted the values ​​in the problem range and around me:

 - (NSString *)temperature:(NSNumber *)temperature { float f = [temperature floatValue]; if (f < 0 && f > -0.5) temperature = [NSNumber numberWithLong:lround(f)]; return [self.temperatureFormatter stringFromNumber:temperature]; } 
+2
source

No, there is no way to configure it for this.

In "10.4 mode", NSNumberFormatter basically just wraps CFNumberFormatter (although it is not a direct paid shell). You can see the list of Formatterter property keys and it’s pretty clear that there is nothing that will do what you want. (Perhaps this is possible in "10.0" mode, it will take a little trial and error to find out. But I doubt that you want to use this.)

So pre-rounding (as Justin Boo suggests) is probably your best bet.

You could, of course, post-process instead. Exactly what you want to do may depend on whether you also want to display -0.00 as 0.00, what you want to do for localizations that do not use "-0", etc. The simplest case will be as simple as this: / p>

 @interface NSNumberFormatter (NegativeZero) - (NSString *)stringFromNumberNoNegativeZero:(NSNumber *)number; @end @implementation NSNumberFormatter (NegativeZero) - (NSString *)stringFromNumberNoNegativeZero:(NSNumber *)number { NSString *s = [self stringFromNumber:number]; if ([s isEqualToString:@"-0"]) return @"0"; return s; } @end 

But if you need something more complex, it will get complicated.

+1
source

Source: https://habr.com/ru/post/917117/


All Articles