views:

108

answers:

1

That looks like a bug in the API:

When my input CGFloat is 0.0, I get this:

Input = 0.000000, Output = +0

When my input CGFloat is 1.0, I get this:

Input = 1.000000, Output = +2

Obviously that's not what I want ;-)

Now here is how I create that NSNumberFormatter object:

    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    [formatter setAlwaysShowsDecimalSeparator:NO];
    [formatter setAllowsFloats:YES];
    [formatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
    [formatter setMinimumFractionDigits:0];
    [formatter setPlusSign:@"+"];
    [formatter setMinusSign:@"-"];
    [formatter setPositivePrefix:@"+"];
    [formatter setNegativePrefix:@"-"];
    [formatter setRoundingMode:NSNumberFormatterRoundUp];

and this is how I let it format my CGFloat of 1.0f:

CGFloat myValue = 1.0f;     
NSNumber *number = [NSNumber numberWithFloat:myValue];
NSLog(@"Input = %f, Output = %@", myValue, [self.inputValueFormatter stringFromNumber:number]);

May be the roundingMode the problem here? Which should I specify? Or is there another cause for this strange behavior?

+1  A: 

Adding this seems to do the trick for me, although I'm not sure why it does:

[formatter setRoundingIncrement: [NSNumber numberWithFloat: 1]];
Ölbaum
I figured out the rounding mode was very bad here. I just don't round it, and it works. Did I mention that number formatting sucks?
HelloMoon
I thought you explicitely wanted to round it up, i.e. 1.1 becomes 2.0. If you want the usual rounding (x.5 and above is rounded up, other values are rounded down), you should use NSNumberFormatterRoundHalfUp I think.
Ölbaum