Guest User

Untitled

a guest
Oct 21st, 2019
80
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // C program for implementation of ftoa()
  2. #include<stdio.h>
  3. #include<math.h>
  4.  
  5. // reverses a string 'str' of length 'len'
  6. void reverse(char *str, int len)
  7. {
  8. int i=0, j=len-1, temp;
  9. while (i<j)
  10. {
  11. temp = str[i];
  12. str[i] = str[j];
  13. str[j] = temp;
  14. i++; j--;
  15. }
  16. }
  17.  
  18. // Converts a given integer x to string str[]. d is the number
  19. // of digits required in output. If d is more than the number
  20. // of digits in x, then 0s are added at the beginning.
  21. int intToStr(int x, char str[], int d)
  22. {
  23. int i = 0;
  24. while (x)
  25. {
  26. str[i++] = (x%10) + '0';
  27. x = x/10;
  28. }
  29.  
  30. // If number of digits required is more, then
  31. // add 0s at the beginning
  32. while (i < d)
  33. str[i++] = '0';
  34.  
  35. reverse(str, i);
  36. str[i] = '\0';
  37. return i;
  38. }
  39.  
  40. // Converts a floating point number to string.
  41. void ftoa(float n, char *res, int afterpoint)
  42. {
  43. // Extract integer part
  44. int ipart = (int)n;
  45.  
  46. // Extract floating part
  47. float fpart = n - (float)ipart;
  48.  
  49. // convert integer part to string
  50. int i = intToStr(ipart, res, 0);
  51.  
  52. // check for display option after point
  53. if (afterpoint != 0)
  54. {
  55. res[i] = '.'; // add dot
  56.  
  57. // Get the value of fraction part upto given no.
  58. // of points after dot. The third parameter is needed
  59. // to handle cases like 233.007
  60. fpart = fpart * pow(10, afterpoint);
  61.  
  62. intToStr((int)fpart, res + i + 1, afterpoint);
  63. }
  64. }
  65.  
  66. // driver program to test above funtion
  67. int main()
  68. {
  69. char res[20];
  70. float n = 233.007;
  71. ftoa(n, res, 4);
  72. printf("\n\"%s\"\n", res);
  73. return 0;
  74. }
RAW Paste Data