5

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

Brock
  • 925
  • 5
  • 9

1 Answers1

6

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
Brock
  • 925
  • 5
  • 9
  • 2
    If you know you want to convert a `Float` to an `Int`, you can search for that type signature on Elm Search, e.g. https://klaftertief.github.io/elm-search/?q=Float%20-%3E%20Int – bdukes Apr 13 '21 at 13:54