#What's the best way to parse a number to float if it can be either float or int?

1 messages · Page 1 of 1 (latest)

stoic needle
#

It seems that float fails for ints, not sure if on purpose or not.

result.try_recover(float.parse(x), fn(_) {
  result.flatten({
    use x <- result.map(int.parse(x))
    Ok(int.to_float(x))
  })
})
unreal briar
#

it is on purpose! a quick way would be to just do both:

case float.parse(x), int.parse(x) {
  Ok(x), _ -> x
  _, Ok(x) -> int.to_float(x)
  _, _ -> Error(Nil)
}

or what you had, written slightly differently

float.parse(x)
|> result.try_recover(fn(_) {
  int.parse(x)
  |> result.map(int.to_float)
})