ern said:
Anybody know a quick and dirty function for going from "547.6458679" to
the integer version 548 ?
i.e.
int returnIntegerEquivalent(char * charNum){
int intNum;
//Do some stuff...
return intNum;
}
I was using the Windows stuff before (ie _gcvt() and atof()).
Thanks,
#include <errno.h>
#include <stdlib.h>
#include <math.h>
#include <stdio.h>
/* making no assumption that s represents an value in the range of an
int, but accepting that some initial portion is supposed to represent
a legal double value. 0 is returned (with errno set) if a problem occurs
with the string to float conversion. */
double floatingstring2floatingint(const char *s)
{
double x, fp, ip;
int sign = 1;
errno = 0;
x = strtod(s, 0);
if (errno)
return 0;
if (x < 0) {
sign = -1;
x = -x;
}
fp = modf(x, &ip);
if (fp >= .5)
ip++;
return sign * ip;
}
int main(void)
{
char s[] = "547.6458679";
char t[] = "-547.6458679";
printf("The initial string (s) is \"%s\n", s);
printf("floatingstring2floatingint(s) returns %g\n",
floatingstring2floatingint(s));
printf("The initial string (t) is \"%s\n", t);
printf("floatingstring2floatingint(t) returns %g\n",
floatingstring2floatingint(t));
return 0;
}
The initial string (s) is "547.6458679
floatingstring2floatingint(s) returns 548
The initial string (t) is "-547.6458679
floatingstring2floatingint(t) returns -548