How to get the exact fractional part from a floating point number as an integer?
How to get the exact fractional part from a floating point number as an integer?
trying to extract the exact fractional part from a floating point number.
Use modf()
or modff()
double modf(double value, double *iptr);
float modff(float value, float *iptr);
The
modf
functions break the argument value into integral and fractional parts, ...
C11 §7.12.6.12 2
#include <math.h>
double value = 1.234;
double ipart;
double frac = modf(value, &ipart);
A better approach for OP's need may be to first round a scaled value and then back into whole and fractional parts.
double value = 254.73;
value = round(value*100.0);
double frac = fmod(value, 100); // fmod computes the floating-point remainder of x/y.
double ipart = (value - frac)/100.0;
printf("%f %f\n", ipart, frac);
254.000000 73.000000
Ref detail: When OP uses 254.73
, this is converted to the nearest float
value which may be 254.729995727539...
.
float f = 254.73;
printf("%.30f\n", f);
// 254.729995727539062500000000000000
You can use sprintf and sscanf to print the value to a string and then extract the fraction. The %*d
scans and discards the first integer of the formatted string. A dot is scanned and then the fraction.
#include <stdio.h>
int main( void)
{
char fp[30];
int fraction;
float f = 254.73f;
sprintf ( fp, "%.2f", f);
sscanf ( fp, "%*d.%d", &fraction);
printf ( "%d\n", fraction);
return 0;
}