Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issues with setMaximumFractionDigits

setMaximumFractionDigits is not working with the following code.

NSString *input=@"80.90";
NSNumberFormatter *numberFormatter=[[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
[numberFormatter setMaximumFractionDigits:2];
NSNumber *number=[numberFormatter numberFromString:input];

number gets converted to 80.90000000000001. but I have put a limit to 2 decimal places. So, how do I get number as 80.90, instead of 80.90000000000001

like image 457
NNikN Avatar asked Dec 09 '22 00:12

NNikN


2 Answers

setMaximumFractionDigits and setMinimumFractionDigits used to formatting a number. or in other words it get applied while converting a number into string i.e. stringFromNumber. So it will not get applied when you are using numberFromString

like image 165
Sunil Pandey Avatar answered Dec 25 '22 04:12

Sunil Pandey


As @SunilPandey mentioned -setMaximumFractionDigits is used for formatting a number. So You can do it like this:

float input = 80.99999;
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setRoundingMode: NSNumberFormatterRoundDown];
[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
[numberFormatter setMaximumFractionDigits:2];

NSString *numberString = [numberFormatter stringFromNumber:[NSNumber numberWithFloat:input]];
[formatter release];

NSLog(@"NumberString: %@", numberString);

Output:

NumberString: 80.99

like image 23
Justin Boo Avatar answered Dec 25 '22 02:12

Justin Boo