Getting the fractional part of a float without using modf()

If I understand your question correctly, you just want the part after the decimal right? You don’t need it actually in a fraction (integer numerator and denominator)?

So we have some number, say 3.14159 and we want to end up with just 0.14159. Assuming our number is stored in float f;, we can do this:

f = f-(long)f;

Which, if we insert our number, works like this:

0.14159 = 3.14159 - 3;

What this does is remove the whole number portion of the float leaving only the decimal portion. When you convert the float to a long, it drops the decimal portion. Then when you subtract that from your original float, you’re left with only the decimal portion. We need to use a long here because of the size of the float type (8 bytes on most systems). An integer (only 4 bytes on many systems) isn’t necessarily large enough to cover the same range of numbers as a float, but a long should be.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)