First, this isn’t a question about precision or anything like that.
My question is, how does the compiler decide how to represent a number?
Let’s take C for example. I write
double d = 4.5632;
How does it pick its binary representation? I know it’s not represented exactly, so how does it choose the closest representable number? Is it done at compile time? Is it done by the CPU or the OS?
Please only answer if you know how this happens, answers like “don’t worry about it” are not helpful. Also, “it depends on the platform” isn’t helpful also, you can pick a platform and explain for that.
The compiler doesn’t decide (typically). The CPU (typically) has a floating-point unit, which requires floating-point values to be represented in a particular format (it’s typically IEEE-754). Of course, it’s possible to emulate an entirely different architecture, in which case the compiler/emulator author is free to pick an entirely different representation. But this isn’t typical.
As to how the specific lexical representation
4.5632is converted to the underlying representation, that’s specified by the C standard. So from section 6.4.4.2 of the C99 standard (I’ve highlighted the most relevant part):This will be done at compile-time (although the standard doesn’t mandate that).