Search code examples
haskellfloating-pointcoercion

recommended way to convert Double -> Float in Haskell


What is the idiomatic way to go Double -> Float?

Is it uncurry encodeFloat . decodeFloat ?

(I am using gloss, this requires Floats)

And what is the recommended way to find an answer to such questions?

I was trying this hoogle query but the answers are all very unhelpful (try it - it has unsafeCoerce at the top of the list)


Solution

  • Use realToFrac :: (Real a, Fractional b) => a -> b.

    It converts from any real number type (like Int, Float or Double) to any fractional type (like Float, Double or Rational).

    Note that even though the general definition of this function (fromRational . toRational) does a slow conversion via the Rational type, there are rewrite rules which use more efficient implementations for conversions between Float and Double.