十进制值四舍五入到ios中的下一个较高值



在我的应用程序中,我接受金额值(float)并保存它。在金额字段中,用户可以输入小数点后的任意数字。但当我读它并保存时,它应该只有小数点后的两位数。这个场景可以正确地使用我的代码。但问题是,如果用户输入值2.468,它将被保存为2.47。但如果用户输入是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;
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]]);
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 numberString具有四舍五入值。。

相关内容

  • 没有找到相关文章