How to extract the decimal part from a floating point number in C?

Binu picture Binu · Feb 1, 2009 · Viewed 217.9k times · Source

How can we extract the decimal part of a floating point number and store the decimal part and the integer part into two separate integer variables?

Answer

Johannes Schaub - litb picture Johannes Schaub - litb · Feb 1, 2009

You use the modf function:

double integral;
double fractional = modf(some_double, &integral);

You can also cast it to an integer, but be warned you may overflow the integer. The result is not predictable then.