Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I obtain the fractional part of a floating-point value?

I have a variable x of type float, and I need its fractional part. I know I can get it with

  • x - floorf(x), or
  • fmodf(x, 1.0f)

My questions: Is one of these always preferable to the other? Are they effectively the same? Is there a third alternative I might consider?

Notes:

  • If the answer depends on the processor I'm using, let's make it x86_64, and if you can elaborate about other processors that would be nice.
  • Please make sure and refer to the behavior on negative values of x. I don't mind this behavior or that, but I need to know what the behavior is.
like image 988
einpoklum Avatar asked Oct 18 '25 13:10

einpoklum


1 Answers

Is there a third alternative I might consider?

There's the dedicated function for it. modff exists to decompose a number into its integral and fractional parts.

float modff( float arg, float* iptr );

Decomposes given floating point value arg into integral and fractional parts, each having the same type and sign as arg. The integral part (in floating-point format) is stored in the object pointed to by iptr.

like image 106
StoryTeller - Unslander Monica Avatar answered Oct 20 '25 05:10

StoryTeller - Unslander Monica



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!