commas.c 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. /*!
  2. * \file lib/gis/commas.c
  3. *
  4. * \brief GIS Library - Comma string functions.
  5. *
  6. * (C) 2001-2014 by the GRASS Development Team
  7. *
  8. * This program is free software under the GNU General Public License
  9. * (>=v2). Read the file COPYING that comes with GRASS for details.
  10. *
  11. * \author GRASS GIS Development Team
  12. *
  13. * \date 1999-2014
  14. */
  15. #include <string.h>
  16. #include <grass/gis.h>
  17. /**
  18. * \brief Inserts commas into a number string.
  19. *
  20. * Examples:
  21. *
  22. * - 1234567 becomes 1,234,567
  23. * - 1234567.89 becomes 1,234,567.89
  24. * - 12345 becomes 12,345
  25. * - 1234 stays 1234
  26. *
  27. * <b>Note:</b> Does not work with negative numbers.
  28. *
  29. * \param[in,out] buf string
  30. * \return 1 if no commas inserted
  31. * \return 0 if commas inserted
  32. */
  33. int G_insert_commas(char *buf)
  34. {
  35. char number[100];
  36. int i, len;
  37. int comma;
  38. while (*buf == ' ')
  39. buf++;
  40. strcpy(number, buf);
  41. for (len = 0; number[len]; len++)
  42. if (number[len] == '.')
  43. break;
  44. if (len < 5)
  45. return 1;
  46. i = 0;
  47. if ((comma = len % 3)) {
  48. while (i < comma)
  49. *buf++ = number[i++];
  50. *buf++ = ',';
  51. }
  52. for (comma = 0; number[i]; comma++) {
  53. if (number[i] == '.')
  54. break;
  55. if (comma && (comma % 3 == 0))
  56. *buf++ = ',';
  57. *buf++ = number[i++];
  58. }
  59. while (number[i])
  60. *buf++ = number[i++];
  61. *buf = 0;
  62. return 0;
  63. }
  64. /**
  65. * \brief Removes commas from number string.
  66. *
  67. * Examples:
  68. * - 1,234,567 becomes 1234567<br>
  69. * - 1,234,567.89 becomes 1234567.89<br>
  70. * - 12,345 becomes 12345<br>
  71. * - 1234 stays 1234
  72. *
  73. * \param[in,out] buf string
  74. * \return
  75. */
  76. void G_remove_commas(char *buf)
  77. {
  78. char *b;
  79. for (b = buf; *b; b++)
  80. if (*b != ',')
  81. *buf++ = *b;
  82. *buf = 0;
  83. }