Rounding off decimal fraction in ios

karan picture karan · Sep 6, 2012 · Viewed 7.4k times · Source
NSNumberFormatter *format = [[NSNumberFormatter alloc]init];
[format setNumberStyle:NSNumberFormatterDecimalStyle];
[format setRoundingMode:NSNumberFormatterRoundHalfUp];
[format setMaximumFractionDigits:2];
NSString *temp = [format stringFromNumber:[NSNumber numberWithFloat:23.4451]];
NSLog(@"%@",temp);

I need round off a six decimal fraction number to two decimal. In iOS I tried the code above. I get the answer 23.5 when I give input as 23.45, but when I give input 23.445 the answer is 23.44.

Could someone clear-up "round half up" in iOS.

Answer

NJones picture NJones · Sep 6, 2012

Interestingly, well at least to me, it is a float precision issue. As rdelmar had suggested in comments.

This problem can be avoided, at least at this precision level, by using a double. For example:

NSNumberFormatter *format = [[NSNumberFormatter alloc]init];
[format setNumberStyle:NSNumberFormatterDecimalStyle];
[format setRoundingMode:NSNumberFormatterRoundHalfUp];
[format setMaximumFractionDigits:2];
[format setMinimumFractionDigits:2];

// With Float:
NSLog(@"%@",[format stringFromNumber:[NSNumber numberWithFloat:23.445]]); // Float
// Logs 23.44
NSLog(@"%@",[format stringFromNumber:[NSNumber numberWithDouble:23.445]]); // Double
// Logs 23.45

So you were not suffering from bad code, just imprecise variables.