0

Given the NSString "1.625", I want to round this to "1.63". How in the world do I do that?

This is what i have now:

NSString *rateString = [NSString stringWithFormat:@"%.2f", [@"1.63" doubleValue]];
NSNumberFormatter * f = [[NSNumberFormatter alloc] init];
[f setNumberStyle:NSNumberFormatterDecimalStyle];
item.rate = [f numberFromString:rateString];;

However, doubleValue converts 1.625 to 1.6249999999 So when I round it to two decimal digits with @"%.2f", I end up with 1.62!

etayluz
  • 15,920
  • 23
  • 106
  • 151
  • possible duplicate of [Rounding numbers in Objective-C](http://stackoverflow.com/questions/752817/rounding-numbers-in-objective-c) – thelaws Jan 13 '15 at 20:31
  • Look into using `NSDecimalNumber` instead of using `double`. – rmaddy Jan 13 '15 at 20:56

2 Answers2

1

If you wanna round to the nearest hundredths, multiply by 100, increment by .5 and divide by 100. Then get the floor of that value.

double rate = [@"1.625" doubleValue];
double roundedNumber = floor(rate * 100 + 0.5) / 100;

NSString *rateString = [NSString stringWithFormat:@"%.2f", roundedNumber];
NSLog(@"rate: %@", rateString);

Running this then outputting the result:

2015-01-13 15:41:08.702 Sandbox[22027:883332] rate: 1.63
Chris
  • 7,270
  • 19
  • 66
  • 110
1

If you need high precision what you really need is NSDecimalNumberclass maybe coupled with NSDecimalNumberHandler if don't need to configure all details, or NSDecimalNumberBehaviors if need absolute control. This is the quickest solution to keep 2 decimal digits (the 'scale' value in handler init):

NSDecimalNumberHandler *handler = [[NSDecimalNumberHandler alloc]initWithRoundingMode:NSRoundBankers
                                                                                scale:2
                                                                     raiseOnExactness:NO
                                                                      raiseOnOverflow:NO
                                                                     raiseOnUnderflow:NO
                                                                  raiseOnDivideByZero:NO];

[NSDecimalNumber setDefaultBehavior:handler];

NSString *string = @"1.63";
NSDecimalNumber *number = [NSDecimalNumber decimalNumberWithString:string];

NSDecimalNumber docs: https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSDecimalNumber_Class/index.html

NSDecimalNumberHandler docs: https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSDecimalNumberHandler_Class/index.html

NSDecimalNumberBehaviors docs: https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Protocols/NSDecimalNumberBehaviors_Protocol/index.html