I would feel much better with using floor
from math.h
:
f = 4.561
if (f>=0) f=f-floor(f);
else f=f-ceil(f);
// here f = 0.561
for these reasons:
As you do not have control over casting to integral type (f-long(f)
) at least I do not know if it is clearly defined as a standard it is using integer part or rounding. Not to mention custom types implementation.
what if your floating value holds bigger number then your integral type can hold? I know there are not that many mantissa bits for fractional part for bigger numbers but you did not specify which floating data-type you are using if 32/64/80/128/256 bits or more so hard to say and if the integer part is bigger then your integral data-type used to cut off the non fractional part then you would be in trouble with f-long(f)
.
PS.
The if statement could be avoided with masking in and out the sign bit before and after the operation. For example on standard 32bit float it looks like this:
float f=4.561; // input value
DWORD *dw=(DWORD*)(&f); // pointer to f as integer type to access bits
DWORD m; // sign storage
m=(*dw)&0x80000000; // store sign bit to m
(*dw)&= 0x7FFFFFFF; // f=fabs(f)
f-=floor(f);
(*dw)|=m; // restore original sign from m
// here f = 0.561
If you do not have DWORD
use any unsigned 32 bit integer instead