NO

Author Topic: fltoa example  (Read 1143 times)

Offline TimoVJL

  • Global Moderator
  • Member
  • *****
  • Posts: 1852
fltoa example
« on: January 31, 2016, 12:49:41 pm »
Nice example from net.
A small modification here:
Code: [Select]
#define WIN32_LEAN_AND_MEAN
#include <windows.h>

// https://github.com/fthorey/swiftler-bones/blob/master/src/libglobal/strutils.c
// https://en.wikibooks.org/wiki/C_Programming/C_Reference/stdlib.h/itoa

/* Source: Wikip├ędia */
/* reverse:  reverse string s in place */
void reverse(char* s, int n)
{
  int i, j;
  char c;
  for (i = 0, j = n - 1; i < j; i++, j--)
  {
    c = s[i];
    s[i] = s[j];
    s[j] = c;
  }
}

/* Adapted from Wikip├ędia */
/* itoa:  convert n to characters in s */
char* itoa(int n, char* s)
{
  int i, sign;

  if ((sign = n) < 0)       /* record sign */
    n = -n;                 /* make n positive */
  i = 0;
  do                        /* generate digits in reverse order */
  {
    s[i++] = n % 10 + '0';  /* get next digit */
  } while ((n /= 10) > 0);  /* delete it */
  if (sign < 0)
    s[i++] = '-';
  s[i] = '\0';
  reverse(s, i);

  return s;
}

#define FLTOA_PRECISION 0.000001

char* fltoa(float f, char *s)
{
  int f_int;
  int f_frac;
  char* const str = s;

  if (f < 0) {
    *s++ = '-';
    f = -f;
  }

  f_int  = f;
  f_frac = (f - f_int) / FLTOA_PRECISION;

  itoa(f_int, s);

  while (*s)
    s++;

  *s++ = '.';

  itoa(f_frac, s);

  while (*s)
    s++;

  while (*(--s) == '0')
    *s = '\0';

  if (*s == '.')
    *s = '\0';

  return str;
}

#ifndef __POCC__
int _fltused; // for msvc
#endif
void __cdecl WinMainCRTStartup(void)
{
double d = 3.141582536;
char s[20];
fltoa(d, s);
MessageBox(0,s,0,MB_OK);
ExitProcess(0);
}
May the source be with you