objective-ccocoansnumberformatter

NSNumberFormatter rounding to negative zero


I'm using NSNumberFormatter to format float values as integer strings, i.e. omitting the fractional part. I find it odd, that numbers in range (-0.5, 0) *open interval end up as -0. As this value will be displayed to the user, I think that negative zero is not appropriate. I have experimented with various combinations of numberStyle and roundingMode without success.

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


Solution

  • I had to do correct this myself. I am using the NSNumberFormatter to display temperature with default numberStyleNSNumberFormatterNoStyle which rounds the numbers to the whole integer, roundingMode set to NSNumberFormatterRoundHalfUp. In the end I did intercept the values in problematic range and round it myself:

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