/contrib/groff/src/libs/libgroff/iftoa.c

https://bitbucket.org/freebsd/freebsd-head/ · C · 73 lines · 47 code · 4 blank · 22 comment · 19 complexity · 07f119df02795bb600c09d84e503cb32 MD5 · raw file

  1. /* Copyright (C) 1989, 1990, 1991, 1992, 2000, 2004
  2. Free Software Foundation, Inc.
  3. Written by James Clark (jjc@jclark.com)
  4. This file is part of groff.
  5. groff is free software; you can redistribute it and/or modify it under
  6. the terms of the GNU General Public License as published by the Free
  7. Software Foundation; either version 2, or (at your option) any later
  8. version.
  9. groff is distributed in the hope that it will be useful, but WITHOUT ANY
  10. WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11. FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
  12. for more details.
  13. You should have received a copy of the GNU General Public License along
  14. with groff; see the file COPYING. If not, write to the Free Software
  15. Foundation, 51 Franklin St - Fifth Floor, Boston, MA 02110-1301, USA. */
  16. #define INT_DIGITS 19 /* enough for 64-bit integer */
  17. #ifdef __cplusplus
  18. extern "C" {
  19. #endif
  20. char *if_to_a(int i, int decimal_point)
  21. {
  22. /* room for a -, INT_DIGITS digits, a decimal point, and a terminating '\0' */
  23. static char buf[INT_DIGITS + 3];
  24. char *p = buf + INT_DIGITS + 2;
  25. int point = 0;
  26. buf[INT_DIGITS + 2] = '\0';
  27. /* assert(decimal_point <= INT_DIGITS); */
  28. if (i >= 0) {
  29. do {
  30. *--p = '0' + (i % 10);
  31. i /= 10;
  32. if (++point == decimal_point)
  33. *--p = '.';
  34. } while (i != 0 || point < decimal_point);
  35. }
  36. else { /* i < 0 */
  37. do {
  38. *--p = '0' - (i % 10);
  39. i /= 10;
  40. if (++point == decimal_point)
  41. *--p = '.';
  42. } while (i != 0 || point < decimal_point);
  43. *--p = '-';
  44. }
  45. if (decimal_point > 0) {
  46. char *q;
  47. /* there must be a dot, so this will terminate */
  48. for (q = buf + INT_DIGITS + 2; q[-1] == '0'; --q)
  49. ;
  50. if (q[-1] == '.') {
  51. if (q - 1 == p) {
  52. q[-1] = '0';
  53. q[0] = '\0';
  54. }
  55. else
  56. q[-1] = '\0';
  57. }
  58. else
  59. *q = '\0';
  60. }
  61. return p;
  62. }
  63. #ifdef __cplusplus
  64. }
  65. #endif