2

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

4 回答 4

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];
于 2013-08-01T06:41:31.833 回答
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 具有四舍五入的值..

于 2013-09-05T09:52:43.410 回答
1

您添加此代码:

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

NSLog(@"%@",[currencyFormatter stringFromNumber:[NSNumber numberWithDouble:2.245]]);
于 2013-08-01T06:36:59.830 回答
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;
于 2013-08-01T06:33:55.710 回答