十进制值四舍五入到ios中的下一个更高的值
在我的应用程序,我接受量值(浮动),并保存它。 在金额字段中,用户可以在小数点后input任意数量的数字。 但是当我读取并保存时,它应该只有小数点后的两位数字。 这个场景适用于我的代码。 但问题是,如果用户input值2.468,它将被保存为2.47。 但如果用户input是2.245,在这种情况下,我需要保存为2.25,但它只能保存为2.24。
和我的代码是
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;
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]];
NSString数字串具有四舍五入的值。
float a=2.245; float b=ceilf(a*100)/100;
要么
NSNumberFormatter *currencyFormatter = [[NSNumberFormatter alloc] init]; [currencyFormatter setNumberStyle:NSNumberFormatterDecimalStyle]; [currencyFormatter setRoundingMode:NSNumberFormatterRoundCeiling]; [currencyFormatter setMaximumFractionDigits:2];
试试这个代码
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;
你添加这个代码:
[currencyFormatter setNumberStyle:NSNumberFormatterDecimalStyle]; [currencyFormatter setRoundingMode:NSNumberFormatterRoundHalfUp]; [currencyFormatter setMaximumFractionDigits:2]; NSLog(@"%@",[currencyFormatter stringFromNumber:[NSNumber numberWithDouble:2.245]]);