I picked up Elixir this May and It has become one of my favorite programming languages. I played with it back in 2014 and I regret dropping it.
This is my proposal for a new general Number Module. Provides a clean abstraction.
* SEE THE ATTACHED FILES FOR EXAMPLES AND MODULE PROTOTYPE*
To my knowledge, If we want to parse a string to a number we currently have four options:
- String.to_float/1
- String.to_integer/1
- Float.parse/1
- Integer.parse/1 or Integer.parse/2
These are great if you already know that the string contains a valid number.
At the moment, The Number module only contains the following functions:
- parse/1 - automatic number parsing to int or float
- parse/2 - explicit number parsing to int or float
- parse/3 - explicit number parsing to int or float but has an extra step.
- is_number/1 - does the string contain a valid number or start with a valid number. Compared to Kernel.is_number/1 where the value has to be in its proper form already
parse/3 accepts three arguments:
- binary - the string you want to convert to a number, implicit parsing.
- data type (atom) - :integer or :float, explicit parsing.
- options - can be a function in the Float and Integer module or pass in the `base` for the Integer.parse/2 function.
My proposal is a one-liner and since it's built on top of the Integer and Float modules
we can utilize their functions in conjunction with parsing the string to a number.
Example:
Parsing user input:
{ bill_amount, _ } = IO.gets("What is the bill amount? ") |> Number.parse()
{ tip_rate, _ ) = IO.gets("What is the tip rate? ") |> Number.parse()
Number.parse( "45.565", :float, ceil: 2 ) would result in {45.57, ""}
Number.parse( "45.565%", :float, ceil: 2 ) would result in {45.57, "%"}
Valid strings return {parsed_number, rest} and invalid strings return :error in tradition to the Integer and Float modules.
* SEE THE ATTACHED FILES FOR MORE EXAMPLES AND MODULE PROTOTYPE*