lostInTransit
lostInTransit

Reputation: 70997

NSNumberFormatter for rounding up float values

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

Thanks.

Upvotes: 2

Views: 8879

Answers (4)

Brad Larson
Brad Larson

Reputation: 170319

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.

Upvotes: 4

Richard Campbell
Richard Campbell

Reputation: 3621

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

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

Upvotes: 1

Zach Langley
Zach Langley

Reputation: 6786

NSString *value = [NSString stringWithFormat:@"%.3f", theFloat];

Upvotes: 10

Lily Ballard
Lily Ballard

Reputation: 185681

myFloat = round(myfloat * 1000) / 1000.0;

Upvotes: 2

Related Questions