RoundOffTest (), кажется, округляется вверх и вниз - PullRequest
2 голосов
/ 16 апреля 2011
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 голосов
/ 16 апреля 2011

Установите 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];
}
...