[Haskell-beginners] Retrieving the decimal portion of a Double

Shawn Willden shawn-haskell at willden.org
Mon Nov 23 10:45:00 EST 2009


On Monday 23 November 2009 07:31:05 am Dominic Sim wrote:
>     I am trying to retrieve the decimal portion of a Double. My code is:
>
>     getDecimal x = x - floor(x)

The problem is that x is a double (or some other kind of floating point or 
fraction), and "floor x" is an integer, and you can't subtract an integer 
from a double.  To convert "floor x" to a double (or to any other relevant 
type), use "fromIntegral", like:

	getDecimal x = x - fromIntegral(floor x)

However, what I'd really suggest is that you use:

	getDecimal x = snd (properFraction x)

or, in pointfree style:

	getDecimal = snd . properFraction

Also, the type signature for getDecimal should be:

	getDecimal :: RealFrac a => a -> a

That will allow it to be used with any Real or Fractional type.

	Shawn.



More information about the Beginners mailing list