2016-07-26

C: Prettyprinted Value aka Controlled Rounding

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
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:

1
2
long size = 3141592535L;
fancy(size, 1000);

No comments :

Post a Comment