RoundOffTest()似乎向上和向下舍入

时间:2011-04-16 04:06:54

标签: objective-c c rounding rounding-error

void RoundOffTest(double number)
{
    // What value would you pass to RoundOffTest() in order to get this output:
    // BEFORE number=1.785000 round=178.000000 (round down)
    // AFTER  NUMBER=1.785000 round=179.000000 (round up)
    //
    // It seems to round it DOWN.
    // But the 2nd line seems to round it UP.
    // Isn't that impossible?  Wouldn't there be NO possible number you could pass
    // this function, and see that output?  Or is there?

    NSLog(@"BEFORE number=%f round=%f (round down)", number, round(number * 100));
    double NUMBER = 1.785000;  
    NSLog(@"AFTER  NUMBER=%f round=%f (round up)  ", NUMBER, round(NUMBER * 100));

}

1 个答案:

答案 0 :(得分:0)

number设置为1.7849995,您将获得所看到的结果。请注意,%f正在打印6个小数位,并且输出会四舍五入到该位数 - 因此1.7849994将无效。

无需舍入的格式

要回答您的评论问题:请使用NSNumberFormatter。我认为所有printf样式格式化器都是圆形的。 NSNumberFormatter提供了7种不同的舍入模式。以下是测试功能的修改版本:

void RoundOffTest(double number)
{
    NSNumberFormatter *formatter = [NSNumberFormatter new];
    [formatter setFormat:@"0.000000"];  // see docs for format strings
    [formatter setRoundingMode:NSNumberFormatterRoundFloor]; // i.e. truncate
    NSString *formatted = [formatter stringFromNumber:[NSNumber numberWithDouble:number]];
    NSLog(@"%@\n", formatted);
    [formatter release];
}
相关问题