code_junkie

Avoid trailing zeroes in printf()

Nov 12th, 2011
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.61 KB | None | 0 0
  1. printf("%1.3f", 359.01335);
  2. printf("%1.3f", 359.00999);
  3.  
  4. 359.013
  5. 359.010
  6.  
  7. 359.013
  8. 359.01
  9.  
  10. printf("%.6g", 359.013); // 359.013
  11. printf("%.6g", 359.01); // 359.01
  12.  
  13. printf("%.6g", 3.01357); // 3.01357
  14.  
  15. char str[50];
  16. sprintf (str,"%.20g",num); // Make the number.
  17. morphNumericString (str, 3);
  18. : :
  19. void morphNumericString (char *s, int n) {
  20. char *p;
  21. int count;
  22.  
  23. p = strchr (s,'.'); // Find decimal point, if any.
  24. if (p != NULL) {
  25. count = 3; // Adjust for more or less decimals.
  26. while (count >= 0) { // Maximum decimals allowed.
  27. count--;
  28. if (*p != '') // If there's less than desired.
  29. break;
  30. p++; // Next character.
  31. }
  32.  
  33. *p-- = ''; // Truncate string.
  34. while (*p == '0') // Remove trailing zeros.
  35. *p-- = '';
  36.  
  37. if (*p == '.') { // If all decimals were zeros, remove ".".
  38. *p = '';
  39. }
  40. }
  41. }
  42.  
  43. float num = 1.33;
  44. printf("%g", num); //output: 1.33
  45.  
  46. printf(%.0d%.4gn", (int)f/10, f-((int)f-(int)f%10));
  47.  
  48. float f = 1234.5678;
  49. printf("%.0f.%0.f", f-0.5, 1000*(f-(int)f)));
  50.  
  51. void EliminateTrailingFloatZeros(char *iValue)
  52. {
  53. char *p = 0;
  54. for(p=iValue; *p; ++p) {
  55. if('.' == *p) {
  56. while(*++p);
  57. while('0'==*--p) *p = '';
  58. if(*p == '.') *p = '';
  59. break;
  60. }
  61. }
  62. }
  63.  
  64. void EliminateTrailingFloatZeros(char *iValue)
  65. {
  66. char *p = 0;
  67. for(p=iValue; *p; ++p) {
  68. if('.' == *p) {
  69. while(*++p);
  70. while('0'==*--p) *p = '';
  71. if(*p == '.') *p = '';
  72. break;
  73. }
  74. }
  75. }
Add Comment
Please, Sign In to add comment