如何舍入小数2

时间:2015-03-30 10:27:44

标签: ios objective-c

如何舍入小数2?

48382,06 + 86106,62 + 83650,07 + 72939,61 = 291078,36

NSNumber *returnSum = 0;

for (int i = 0; i < [arraySum count]; i++) {
        PayDoc *payDoc = (PayDoc*)([arraySum objectAtIndex:i]);
        returnSum = [NSNumber numberWithFloat:[returnSum floatValue]+[payDoc.SOBTR floatValue]];
    }

回答结果我的代码returnSum = 291078,38

4 个答案:

答案 0 :(得分:3)

使用NSDecimalNumber。将scale设为2,将roundingMode设为NSRoundPlain

NSDecimalNumber *returnSum = [[NSDecimalNumber alloc] initWithFloat:0.0f];

for (PayDoc *payDoc in arraySum) {

        NSDecimalNumber *sobtr = [[NSDecimalNumber alloc] initWithFloat:payDoc.SOBTR.floatValue];
        returnSum = [returnSum decimalNumberByAdding:sobtr withBehavior:[NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:NSRoundPlain scale:2 raiseOnExactness:YES raiseOnOverflow:YES raiseOnUnderflow:YES raiseOnDivideByZero:YES]];
}

我测试了上述值,它给出 291078.36

答案 1 :(得分:1)

您是否尝试过以下操作?

returnSum = @(  roundf([returnSum floatValue] * 100) / 100 + roundf([payDoc.SOBTR floatValue] * 100) / 100  );

这将导致浮点数仅小于点后具有两位数(大约......),而不是像其他评论和答案所示只显示两位数。

或者,如果你不想要对浮点数进行舍入,只想删除十进制数字,你可以写

returnSum = @(  (int)([returnSum floatValue] * 100) / 100.0 + (int)([payDoc.SOBTR floatValue] * 100) / 100.0  );

答案 2 :(得分:0)

使用[NSNumber numberWithInt:[returnSum floatValue]+[payDoc.SOBTR floatValue]];

答案 3 :(得分:-1)

最好的做法如下:

NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];

[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
[formatter setMaximumFractionDigits:2];
[formatter setRoundingMode: NSNumberFormatterRoundUp];

NSString *numberString = [formatter stringFromNumber:[NSNumber numberWithFloat:[returnSum floatValue]+[payDoc.SOBTR floatValue]]];

NSLog(@"Result...%@",numberString);