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, ""}
1
  • 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. Commented Dec 4, 2016 at 12:52

1 Answer 1

3

Convert Elixir string to integer or float

Maybe you should use something like

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

or

elem Float.parse("1"), 0
Sign up to request clarification or add additional context in comments.

5 Comments

It might be helpful to know why the second element of the tuple can be discarded here.
iex(1)> Float.parse("56.5xyz") {56.5, "xyz"}
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.
Do you know why String.to_float("1") is not working?
As per the documentation, String.to_float: 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.