Dec 29, 2009

(Objective-c)How to round a number

Here is a solution to round a float number:

NSString *pi = @"3.14159265";
int floatSize = 3;
NSDecimalNumber *numericValue = [NSDecimalNumber decimalNumberWithString:pi];
NSDecimalNumberHandler *roundingStyle = [NSDecimalNumberHandler 
decimalNumberHandlerWithRoundingMode:
NSRoundBankers scale:floatSize raiseOnExactness:NO raiseOnOverflow:NO 
raiseOnUnderflow:NO 
raiseOnDivideByZero:NO];
NSDecimalNumber *roundedNumber = [numericValue 
decimalNumberByRoundingAccordingToBehavior:
roundingStyle];

or

NSString *pi = @"3.14159265";
NSString *roundedNumber = [[NSString alloc] initWithFormat:
@"%.3f",[pi floatValue]];

Result: 3.142

1 comment:

Inturbidus said...

Thank you so much! This is the only place I could find real rounding without formatters, and other non-sense.