Search code examples
jsonfloating-pointelm

How do I parse a String to a Float?


I need to consume a json source that represents floats as strings* and I can't figure out how.

It is almost easy:

Json.Decode.map String.toFloat Json.Decode.string

However, that produces a Maybe Float and I'd prefer it fail altogether if it cant decode the string.

(*) The reason for this is that the real datatype is Decimal, so "1.5" != "1.50". My application doesn't have to care though.


Solution

  • You can either install elm-community/json-extra and use Json.Decode.Extra.parseFloat

    or just copy its implementation

    fromMaybe : String -> Maybe a -> Decode.Decoder a
    fromMaybe error val =
        case val of
            Just v ->
                Decode.succeed v
    
            Nothing ->
                Decode.fail error
    
    parseFloat : Decode.Decoder Float
    parseFloat =
        Decode.string |> Decode.andThen (String.toFloat >> fromMaybe "failed to parse as float")