fork download
  1. #include <math.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4.  
  5. double round_to_n_digits_1(double x, int n)
  6. {
  7. double scale = pow(10.0, ceil(log10(fabs(x))) + n);
  8.  
  9. return round(x * scale) / scale;
  10. }
  11.  
  12. double round_to_n_digits_2(double x, int n)
  13. {
  14. char buff[32];
  15.  
  16. sprintf(buff, "%.*g", n, x);
  17.  
  18. return atof(buff);
  19. }
  20.  
  21. int main(void)
  22. {
  23. double x = 0.0501;
  24.  
  25. printf("%g\n", round_to_n_digits_1(x, 1));
  26. printf("%g\n", round_to_n_digits_2(x, 1));
  27.  
  28. return 0;
  29. }
Success #stdin #stdout 0s 5308KB
stdin
Standard input is empty
stdout
0
0.05