Search code examples
haskellghci

How to read an integer written in exponential form with Haskell?


To read an integer written in decimal form is quite simple :

Prelude> read "1000000000" :: Int
1000000000

But how to read an integer written in exponetial form ?

Prelude> read "10e+9" :: Int
*** Exception: Prelude.read: no parse

Is there a function in the Prelude to do that, or do we need to parse the expression?

Thanks for any reply.


Solution

  • Depending on the exact format of the string, you could just read it into a floating point type:

    > read "10e+9" :: Double
    1.0e10
    

    then convert to an integral type -- I'd recommend Integer instead of Int:

    > floor (read "10e+9" :: Double) :: Integer
    10000000000