fork(3) download
  1. #include <cstdio>
  2. #include <cmath>
  3.  
  4. //Print-format a 32-bit float by exploiting exponent
  5. //Blog post: http://a...content-available-to-author-only...b.io/print-fp.html
  6.  
  7. void print_fp( float number, int digits ) {
  8. union {
  9. float d;
  10. int u;
  11. };
  12.  
  13. d = number;
  14.  
  15. //deal with sign
  16. bool minus = u >> 31;
  17. u = u & ~(1 << 31);
  18.  
  19. //calculate base-10 exponent
  20. double exp = (u >> 23) - 127;
  21. double exp10 = exp / log2( 10.0 );
  22.  
  23. //adjust the number
  24. u = (u & ~(0xFF << 23)) | (127 << 23);
  25. double d2 = double(d) * pow( 10.0, exp10 - int(exp10) );
  26. if( d2 >= 10.0 ) { d2 = d2 / 10.0; exp10+=1.0; }
  27. if( d2 < 1.0 ) { d2 = d2 * 10.0; exp10-=1.0; }
  28.  
  29. //print sign
  30. if( minus ) printf("-");
  31.  
  32. //print integer part
  33. int i = int( d2 );
  34. printf("%.1d.", i);
  35. d2 = d2 - i;
  36.  
  37. while( digits-- ) {
  38. d2 = d2 * 10.0;
  39. int i = int( d2 );
  40. printf("%.1d", i);
  41. d2 = d2 - i;
  42. }
  43.  
  44. //print exponent part
  45. printf("e%d\n", int(exp10));
  46. }
  47.  
  48. int main() {
  49.  
  50. double d;
  51.  
  52. d = 8.589973e9;
  53. printf("%.10f\n", d);
  54. print_fp( d , 10 );
  55.  
  56. d = 8.589974e9;
  57. printf("%.10f\n", d);
  58. print_fp( d , 10 );
  59.  
  60. }
  61.  
Success #stdin #stdout 0s 3456KB
stdin
Standard input is empty
stdout
8589973000.0000000000
8.5899735040e9
8589974000.0000000000
8.5899735040e9