1

Is there a method that takes in a float string and converts it to a single float. It must also handle strings without . like "1"

String.to_float does not handle "1"

iex(5)> String.to_float("1")
** (ArgumentError) argument error
:erlang.binary_to_float("1")
iex(5)> String.to_float("1.0")
1.0

Float.parse handles "1", but returns a tuple.

iex(4)> Float.parse("1")
{1.0, ""}
toftis
  • 1,070
  • 9
  • 26
  • 1
    The tuple is so it can return the float that it parsed, and the remainder of the string that it didn't know what to do with. That is expected with a parser. Just use the first value from the tuple. Or create a wrapper function if you plan on doing it a lot and don't care for the remainder string. – Justin Wood Dec 04 '16 at 12:52

1 Answers1

3

Convert Elixir string to integer or float

Maybe you should use something like

{res, _} = Float.parse("1")

or

elem Float.parse("1"), 0
Community
  • 1
  • 1
  • 1
    It might be helpful to know why the second element of the tuple can be discarded here. – Patrick Oscity Dec 04 '16 at 14:54
  • `iex(1)> Float.parse("56.5xyz") {56.5, "xyz"}` – Artyom Malyshev Dec 04 '16 at 14:59
  • 4
    I'd prefer to use `{res, ""} = Float.parse(float_as_string)` if `float_as_string` is not expected to have trailing rest. This way, the code fails fast if your assumption is not met. – helios35 Dec 04 '16 at 15:18
  • Do you know why `String.to_float("1")` is not working? – toftis Dec 04 '16 at 20:48
  • As per the documentation, [String.to_float](http://elixir-lang.org/docs/stable/elixir/String.html#to_float/1): `string` must be the string representation of a float (Remember that Floating-point numbers must have at least one digit before and after the decimal point). If a string representation of an integer wants to be used, then `Float.parse/1` should be used instead, otherwise an argument error will be raised. – Rafa Paez Dec 04 '16 at 22:44