Page 1 of 1

Fraction part of a double

Posted: Mon Mar 31, 2008 3:05 pm
by Capella
Is there any simple way to get the fraction part out from a double?
The result must be a double as well.

Posted: Mon Mar 31, 2008 3:15 pm
by eesau

Code: Select all

Alpha . d = 123456.789
Omega . d = Alpha - Int ( Alpha )

Debug Omega

Posted: Mon Mar 31, 2008 3:16 pm
by milan1612
Another way using Round():

Code: Select all

doub.d = 3.14159265
Debug doub - Round(doub, 0)

Procedure Fraction

Posted: Mon Mar 31, 2008 4:12 pm
by Capella
Thanks. I realised that there was no inbuilt function for this so I wrote a procedure as follows...

Code: Select all

Procedure.d Fraction (innumber.d)
    absnumber.d = Abs (innumber.d)
    fraction.d = absnumber - Round (absnumber, 0)
    ProcedureReturn fraction.d
EndProcedure
...since it must work with negative numbers as well.

Re: Procedure Fraction

Posted: Mon Mar 31, 2008 9:17 pm
by Demivec
Capella wrote:Thanks. I realised that there was no inbuilt function for this so I wrote a procedure as follows...

Code: Select all

Procedure.d Fraction (innumber.d)
    absnumber.d = Abs (innumber.d)
    fraction.d = absnumber - Round (absnumber, 0)
    ProcedureReturn fraction.d
EndProcedure
...since it must work with negative numbers as well.
Wouldn't the fractional part need to match the sign of the number (i.e. Fraction(-3.14) = -0.14) ?

If so, your code doesn't handle that properly, but eesau's does:

Code: Select all

Alpha . d = 123456.789
Omega . d = Alpha - Int ( Alpha )

Debug Omega
This is because Round() only knows to round up or down and not whether to round towards or away from zero. Int() avoids this problem by truncating the fractional part (moving the number towards zero). eesau's code could be rewritten as:

Code: Select all

Procedure.d Fraction (innumber.d)
    ProcedureReturn innumber - Int (innumber)
EndProcedure

fraction of a double

Posted: Tue Apr 01, 2008 1:49 pm
by Capella
Mathematically speaking you're right. But Since the integer part of the number shows the signum (+/-) of the number there's no need for the fractional part of the same number to show this.

Posted: Tue Apr 01, 2008 2:13 pm
by Derek
Good point. :lol:

Posted: Tue Apr 01, 2008 3:19 pm
by Kaeru Gaman
I think he thought about the signum within the calculation.

but -4.5 - -4.0 is -0.5, so no need to worry about.