如何将字符串解析为浮点数?

4

我需要消费一个JSON数据源,其中数字类型的float表示为string类型,但我不知道该如何操作。

这个问题几乎可以轻松解决:

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

然而,这会产生一个Maybe Float,如果无法解码字符串,我更希望它完全失败。

(*) 这样做的原因是真实的数据类型是 Decimal,所以 "1.5" != "1.50"。不过我的应用程序并不在意这一点。

2个回答

5
你可以选择安装 elm-community/json-extra 并使用 Json.Decode.Extra.parseFloat,或者直接复制其实现。
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")

1
另一个使得fromMaybe不必要的选项:
floatDecoder : Json.Decoder Float
floatDecoder =
    Json.string |> Json.andThen (String.toFloat >> Maybe.withDefault 0.0 >> Json.succeed)

只是以防对其他人有所帮助 ;)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接