[Haskell-cafe] round function

Sebastian Sylvan sebastian.sylvan at gmail.com
Sun Feb 12 18:35:02 EST 2006

On 2/12/06, Chatzianastassiou Achilleas <achatzianastassiou at hotmail.com> wrote:
> In addition to my previous quote, I don't understand the user of
> fromIntegral
> At the prelude, when i type i.e. fromIntegral 4 it returns 4
> Thanks

fromIntegral is overloaded. It will convert an Integral value (such as
Int or Integer) to a numeric value (such as Double, Float, but also
Integer and Int). When you type "fromIntegral 4" it will default the 4
to be an Integer, and it will default the result to be an integer as
Try typing "fromIntegral 4 :: Double", indicating that the result
should be a double, that will give you 4.0.

I think this version will work better... Take the logarithm (in base
10) to find out how many digits to the left of the decimal point there
is (and subract it from the "shift" amount). This can give negative
shifts, so we use (**) instead of (^) since the latter can't deal with
negative exponents.

myround n s = fromIntegral (round (n * factor)) / factor
   where shift = s - (floor (logBase 10 n)  + 1)
             factor = 10 ** fromIntegral shift

Sebastian Sylvan
UIN: 44640862

More information about the Haskell-Cafe mailing list