Sava Mazăre Sava Mazăre - 2 months ago 9x
Objective-C Question

Disable rounding up in NSNumberFormatter (working with locale)

I am working with several locale numbers. Example:

  1. 1.234.567,89 - German

  2. 1'234'567.89 - Switzerland

  3. 1,234,567.89 - US

My code rounds UP the last digit after decimal separator:

NSNumberFormatter *formatter = [[[NSNumberFormatter alloc] init] autorelease];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
[formatter setLocale:[NSLocale currentLocale]];
[formatter setMinimumFractionDigits:2];
[formatter setMaximumFractionDigits:2];

double myValue = [[formatter numberFromString:@"123.458"] doubleValue];
double myValue2 = [[formatter numberFromString:@"123.444"] doubleValue];

NSString *rezult = [formatter stringFromNumber:[NSNumber numberWithDouble:myValue]];
NSString *rezult2 = [formatter stringFromNumber:[NSNumber numberWithDouble:myValue2]];

NSLog(@"rezult = %@", rezult); //gives 123.46 - incorrect
NSLog(@"rezult2 = %@", rezult2);//gives 123.44 - correct

Please suggest how to prevent rounding up.

Keep in mind that I cannot do it like this:

double aDouble = 1234.56789;
NSString *stri = [NSString stringWithFormat:@"%.2f", aDouble];
NSLog(@"%@", stri); //result is 1234.56 - correct (not rounded up to 1234.57)

...because I have to set that *stri using *formatter (see above).

I guess there must be some additional settings to
, isn't it?

Thanks in advance.


Solution: after declaring NSNumberFormatter, say also:

[formatter setRoundingMode: NSNumberFormatterRoundDown];

Thanks to @Price for the fast solution. Subject closed.


You can add this:

[formatter setRoundingMode: NSNumberFormatterRoundDown];