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)); }
Asked
Active
Viewed 169 times
2

Robin
- 21
- 3
1 Answers
0
Set number
to 1.7849995
and you'll get the result you see. Note that %f
is printing 6 decimal places, and that the output is rounded to that number of places - so 1.7849994
will not work.
Formatting without rounding
To answer your comment question: use NSNumberFormatter
. I think all the printf
style formatters round. NSNumberFormatter
provides 7 different rounding modes. Here is a modified version of your test function:
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];
}

CRD
- 52,522
- 5
- 70
- 86
-
So how do I see a number WITHOUT any rounding? I didn't know %f also did built-in rounding. I just need to see "6 decimal places" as-is. No rounding off. – Robin Apr 16 '11 at 14:55