Search code examples
c++floating-pointroundingstatic-castfloating-point-conversion

Will int to double conversion round up, down or to nearest double?


Simple question: Will the conversion from an int, say 100, to a double "round" up or down to the next double or will it always round to the nearest one (smallest delta)?

e.g. for static_cast<double>(100):

Casting from int to double

Which way will it cast if d2 < d1?

Bonus question: Can I somehow force the processor to "round" down or up to the closes double using special functions? As I see it, there's no floor<double> or ceil<double> unfortunately.


Solution

  • Note that a 32-bit int can be represented exactly by a 64-bit IEEE 754 double (it can actually represent up to 53-bit integers precisely).

    If you're using an integer that is larger than can be represented by your floating point type then the rules at Real floating-integer conversions apply:

    • if the value can be represented, but cannot be represented exactly, the result is the nearest higher or the nearest lower value (in other words, rounding direction is implementation-defined), although if IEEE arithmetic is supported, rounding is to nearest. It is unspecified whether FE_INEXACT is raised in this case.
    • if the value cannot be represented, the behavior is undefined, although if IEEE arithmetic is supported, FE_INVALID is raised and the result value is unspecified.

    There is no c++ standard function to control the rounding mode, most implementations will use the IEEE round to nearest.