fork(51) download
  1. #include <stdio.h>
  2. #include <math.h>
  3.  
  4. double round_to_digits(double value, int digits)
  5. {
  6. if (value == 0.0) // otherwise it will return 'nan' due to the log10() of zero
  7. return 0.0;
  8. double factor = pow(10.0, digits - ceil(log10(fabs(value))));
  9. return round(value * factor) / factor;
  10. }
  11.  
  12. int main(void) {
  13.  
  14. printf("%.52g\n", round_to_digits(0.0, 6));
  15. printf("%.52g\n", round_to_digits(-123.23344553, 6));
  16. printf("%.52g\n", round_to_digits(-123.23344553, 6));
  17. printf("%.52g\n", round_to_digits(-123.23344553, 7));
  18. printf("%.52g\n", round_to_digits(-123.23344553, 8));
  19. return 0;
  20. }
Success #stdin #stdout 0s 2052KB
stdin
Standard input is empty
stdout
0
-123.23300000000000409272615797817707061767578125
-123.23300000000000409272615797817707061767578125
-123.2334000000000031604940886609256267547607421875
-123.23345000000000482032191939651966094970703125