tags:

views:

1640

answers:

4

Hi

I have a CGFloat value which I want to round to 3 digits after the decimal point. How should I do this?

Thanks.

+1  A: 
myFloat = round(myfloat * 1000) / 1000.0;
Kevin Ballard
Thanks Kevin. But while printing I still get a .xxx000. Its the 000 I don't want. Thats why I was asking if I need to use NSNumberFormatter
lostInTransit
+1  A: 

Try formatting the float as "%5.3f" or similar for display purposes

...like Zach Langley did in his better answer.

Richard Campbell
+4  A: 
NSString *value = [NSString stringWithFormat:@"%.3f", theFloat];
Zach Langley
A: 

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.

Brad Larson