void fancy(long l, long nearest)
{
char suffix[2] = "";
long mod, val = l;
float f;
if(val < 1500) /* Too small to pretty print. */
{
printf("%li B", val);
} else {
mod = val % nearest;
/* Where are we in the range? */
if(mod >= (nearest - mod))
{ // hi - we are at or above the 50% of the [0-nearest[ range.
// add the difference to reach upper nearest.
val += (nearest - mod);
} else { // lo
// substract the difference to reach lower nearest.
val -= mod;
}
if(val < 1100000L)
{
f = (float)val / 1000;
suffix[0] = 'K';
} else if(val < 1100000000L)
{
f = (float)val / 1000000;
suffix[0] = 'M';
} else {
f = (float)val / 1000000000;
suffix[0] = 'G';
}
printf("%.2f %sB", f, suffix); // Here you can play with the format.
}
}
Usage:
long size = 3141592535L; fancy(size, 1000);
No comments :
Post a Comment