In my app, am accepting amount value(float) and saving it. In the amount field, the user may enter any number of digits after decimal point. But when i read it and save, it should be only two digits after the decimal point. this scenario works properly with my code. but the problem is, if the user enters the value 2.468, it is saved as 2.47. but if the user input is 2.245, in this case i need to be saved as 2.25 but it gets saved as 2.24 only.
and my code is
AmountValue = [NSString stringWithFormat:@"%f",[AmountTxt1.text floatValue]];
float Rate_int = [AmountValue floatValue];
NSNumberFormatter *currencyFormatter = [[NSNumberFormatter alloc] init];
[currencyFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
NSString *str1 = [NSString stringWithFormat:@"%@",[currencyFormatter stringFromNumber:[NSNumber numberWithFloat:Rate_int]]];
TotalAmtTxt.text = str1;
float a=2.245;
float b=ceilf(a*100)/100;
or
NSNumberFormatter *currencyFormatter = [[NSNumberFormatter alloc] init];
[currencyFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
[currencyFormatter setRoundingMode:NSNumberFormatterRoundCeiling];
[currencyFormatter setMaximumFractionDigits:2];
try this Code..
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
[formatter setMaximumFractionDigits:2];
[formatter setRoundingMode: NSNumberFormatterRoundHalfUp];
NSString *numberString = [formatter stringFromNumber:[NSNumber numberWithFloat:Rate_int]];
TotalAmt.txt = numberString;
you add this code:
[currencyFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
[currencyFormatter setRoundingMode:NSNumberFormatterRoundHalfUp];
[currencyFormatter setMaximumFractionDigits:2];
NSLog(@"%@",[currencyFormatter stringFromNumber:[NSNumber numberWithDouble:2.245]]);
double Rate_int1 = [input doubleValue];
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
[formatter setRoundingMode: NSNumberFormatterRoundHalfUp];
[formatter setMaximumFractionDigits:2];
NSString *numberString = [formatter stringFromNumber:[NSNumber numberWithDouble:Rate_int1]];
The NSString numberString has the rounded off value..