Question

**NSLog(@"%0.2f", 1.345); // output 1.34**
NSLog(@"%0.2f", 1.3451);// output 1.35
NSLog(@"%0.2f", round(1.345 * 100)/100.);//output 1.35

Why the first line output 1.34?!!

=======================================

Updated:

NSLog(@"%.2f", round([@"644.435" doubleValue] * 100) / 100); // output 644.43, 

but

NSLog(@"%.2f", round([@"6.435" doubleValue] * 100) / 100); // output 6.44? 

If I want to convert a NSString to keep two digit after the point, would you please advise how to convert?

Was it helpful?

Solution

Because 1.345 cannot be represented exactly in IEEE754. More than likely, it's something like 1.34444444449 which, when printed, gives you 1.34.

If you search for things like ieee754, precision and floating point, one of the billion or so articles should be able to enlighten you :-)

Look particularly for: What every computer scientist should know about floating point.

Going into a little more detail, examine the following C program:

#include <stdio.h>
int main (void) {
    float f = 1.345f;
    double d = 1.345;
    printf ("f = %.20f\nd = %.20lf\n", f, d);
    return 0;
}

The output of this is:

f = 1.34500002861022949219
d = 1.34499999999999997335

So the float value is a little above 1.345 and the double (which is what you get when you specify 1.345 without the f suffix) is a little below.

That explains why you're seeing it truncated to 1.34 rather than rounded to 1.35.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top