For a simple project I have to make large numbers (e.g. 4294967123) readable, so I'm writing only the first digits with a prefix (4294967123 -> 4.29G, 12345 -> 12.34K etc.)
The code (simplified) looks like this:
const char* postfixes=" KMGT";
char postfix(unsigned int x)
{
return postfixes[(int) floor(log10(x))];
}
It works, but I think that there's a more elegant/better solution than computing the full precision logarithm, rounding it and casting it down to an int again.
Other solutions I thought of:
int i=0;
for(; x >= 1000 ; ++i) x/=1000;
return postfixes[i];
(This is significantly slower, but easier to read)
The numbers are distributed between according to Benford's Law and the number should be treated as unsigned 64 bit-number, as there should be no rounding error near 10^x (e.g. in python math.log(1000,10)
returns 2.999996, which gets floored to 2).
Is there any fast, accurate other way I'm missing?