Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Elixir string to integer or float

Tags:

elixir

I need to convert a string to a floating point value or an integer. There was no method such as,

string_to_integer 
like image 702
Lahiru Avatar asked Mar 22 '14 10:03

Lahiru


People also ask

How to Convert string to integer in Elixir?

Idiom #22 Convert string to integerint i = int. Parse(s); Throws an error if s can't be converted. int can be replaced with any number data type.

Can you convert string to int or float?

We can convert a string to float in Python using float() function. It's a built-in function to convert an object to floating point number. Internally float() function calls specified object __float__() function.

How do you convert float to int in Elixir?

Use trunc(2.0) or round(2.0) . Those are auto-imported since they are part of Kernel and they are also allowed in guard clauses. FWIW: round/1 still returns a Float at this point -- trunc/1 will convert to Integer.

Is Elixir a float?

Numbers in Elixir Elixir recognizes two kinds of numbers: integers and floating point numbers (often called floats).


2 Answers

Check Integer.parse/1 and Float.parse/1.

like image 200
José Valim Avatar answered Nov 02 '22 20:11

José Valim


In addition to the Integer.parse/1 and Float.parse/1 functions which José suggested you may also check String.to_integer/1 and String.to_float/1.

Hint: See also to_atom/1,to_char_list/1,to_existing_atom/1for other conversions.

like image 42
Szymon Jeż Avatar answered Nov 02 '22 19:11

Szymon Jeż