Search code examples
floating-pointintegerelm

How do I convert a Float to an Int in Elm?


If I have a Float value and I want a Int to use elsewhere how do I make that conversion?


Solution

  • Elm makes it very easy to convert between values!

    (Note: Because Elm is functional and all variables are immutable, the value is not actually converted, rather a new equivalent value is created.)

    All you have to do is choose what you want to do with the decimals!

    Round do the nearest integer with round

    1.5 |> round -- 2 : Int
    

    Round up with ceiling

    1.5 |> ceiling -- 2 : Int
    

    Round down with floor

    1.5 |> floor -- 1 : Int
    

    Ignore the deimals with truncate

    1.5 |> truncate -- 1 : Int
    

    Converting back is just as easy using toFloat

    1 |> toFloat -- 1.0 : Float