Fraction part of a double

Just starting out? Need help? Post your questions and find answers here.
Capella
User
User
Posts: 16
Joined: Wed Mar 19, 2008 5:32 pm

Fraction part of a double

Post by Capella »

Is there any simple way to get the fraction part out from a double?
The result must be a double as well.
eesau
Enthusiast
Enthusiast
Posts: 589
Joined: Fri Apr 27, 2007 12:38 pm
Location: Finland

Post by eesau »

Code: Select all

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

Debug Omega
milan1612
Addict
Addict
Posts: 894
Joined: Thu Apr 05, 2007 12:15 am
Location: Nuremberg, Germany
Contact:

Post by milan1612 »

Another way using Round():

Code: Select all

doub.d = 3.14159265
Debug doub - Round(doub, 0)
Windows 7 & PureBasic 4.4
Capella
User
User
Posts: 16
Joined: Wed Mar 19, 2008 5:32 pm

Procedure Fraction

Post 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.
User avatar
Demivec
Addict
Addict
Posts: 4283
Joined: Mon Jul 25, 2005 3:51 pm
Location: Utah, USA

Re: Procedure Fraction

Post 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
Capella
User
User
Posts: 16
Joined: Wed Mar 19, 2008 5:32 pm

fraction of a double

Post 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.
Derek
Addict
Addict
Posts: 2354
Joined: Wed Apr 07, 2004 12:51 am
Location: England

Post by Derek »

Good point. :lol:
User avatar
Kaeru Gaman
Addict
Addict
Posts: 4826
Joined: Sun Mar 19, 2006 1:57 pm
Location: Germany

Post 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.
oh... and have a nice day.
Post Reply