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

时间:2013-08-01 06:25:58

标签: iphone ios currency rounding

在我的应用中,我接受金额(浮动)并保存。在金额字段中,用户可以在小数点后输入任意数量的位数。但是当我读它并保存时,它应该只是小数点后的两位数。此方案适用于我的代码。但问题是,如果用户输入值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;

4 个答案:

答案 0 :(得分:2)

float a=2.245;
float b=ceilf(a*100)/100; 

NSNumberFormatter *currencyFormatter = [[NSNumberFormatter alloc] init];
    [currencyFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
    [currencyFormatter setRoundingMode:NSNumberFormatterRoundCeiling];
    [currencyFormatter setMaximumFractionDigits:2];

答案 1 :(得分:1)

试试这个代码..

 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;

答案 2 :(得分:1)

你添加这段代码:

[currencyFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
[currencyFormatter setRoundingMode:NSNumberFormatterRoundHalfUp];
[currencyFormatter setMaximumFractionDigits:2];

NSLog(@"%@",[currencyFormatter stringFromNumber:[NSNumber numberWithDouble:2.245]]);

答案 3 :(得分:1)

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具有舍入值..