You can isolate the fractional part of a float
by using the function modff
in <math.h>
, which returns the fractional part as the function's return value and the whole-number part as an argument by reference:
float f = 3.141592f;
float numpart, fracpart;
fracpart = modff(f, &numpart);
Once you're done that, you can create a string with a conventional string-building function:
char buf[100];
snprintf(buf, 100, "%f", fracpart);
Another option is converting the entire float
to a string, and then using strchr(float_str, '.')
to isolate the decimal part:
char floatbuf[100], decibuf[100], *p;
float f = 3.141592f;
snprintf(floatbuf, 100, "%f", f);
if ((p = strchr(floatbuf, '.')) != NULL)
{
strcpy(decibuf, p + 1);
puts(decibuf);
}