Search code examples
c++floating-pointrounding

How to round a double to an int?


I have a double (call it x), meant to be 55 but in actuality stored as 54.999999999999943157 which I just realised.

So when I do

double x = 54.999999999999943157;
int y = (int) x;

y = 54 instead of 55!

This puzzled me for a long time. How do I get it to correctly round?


Solution

  • add 0.5 before casting (if x > 0) or subtract 0.5 (if x < 0), because the compiler will always truncate.

    float x = 55; // stored as 54.999999...
    x = x + 0.5 - (x<0); // x is now 55.499999...
    int y = (int)x; // truncated to 55
    

    C++11 also introduces std::round, which likely uses a similar logic of adding 0.5 to |x| under the hood (see the link if interested) but is obviously more robust.

    A follow up question might be why the float isn't stored as exactly 55. For an explanation, see this stackoverflow answer.