Hi
I have a CGFloat value which I want to round to 3 digits after the decimal point. How should I do this?
Thanks.
Hi
I have a CGFloat value which I want to round to 3 digits after the decimal point. How should I do this?
Thanks.
Try formatting the float as "%5.3f" or similar for display purposes
...like Zach Langley did in his better answer.
NSString *value = [NSString stringWithFormat:@"%.3f", theFloat];
If you want to go the NSDecimalNumber route, you can use the following:
NSDecimalNumber *testNumber = [NSDecimalNumber numberWithDouble:theFloat];
NSDecimalNumberHandler *roundingStyle = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:NSRoundBankers scale:3 raiseOnExactness:NO raiseOnOverflow:NO raiseOnUnderflow:NO raiseOnDivideByZero:NO];
NSDecimalNumber *roundedNumber = [testNumber decimalNumberByRoundingAccordingToBehavior:roundingStyle];
NSString *stringValue = [roundedNumber descriptionWithLocale:[NSLocale currentLocale]];
This will use bankers' rounding to 3 decimal digits: "Round to the closest possible return value; when halfway between two possibilities, return the possibility whose last digit is even. In practice, this means that, over the long run, numbers will be rounded up as often as they are rounded down; there will be no systematic bias." Additionally, it will use a locale-specific decimal separator (".", ",", etc.).
However, if you have a numerical value like 12.5, it will return "12.5", not "12.500", which may not be what you're looking for.