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
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With