pashie_
pashie_

Reputation: 11

I am trying to perform mathematical operations to inputed data in elixir but its throwing an arithmetic error

I am new to elixir, I am trying to perform mathematical operations on received data in this case, calculate the tithe of salary got from the user and its throwing this error:

** (ArithmeticError) bad argument in arithmetic expression
    m.ex:11: M.calc/0*

here is my code

def calc do
  salary = IO.gets("What is your salary?") |> String.trim
  x = salary
  IO.puts "Your tithe this month is: #{(x * 0.01)}"
end

Upvotes: 1

Views: 198

Answers (1)

sbacarob
sbacarob

Reputation: 2212

The reason you're getting this error is that IO.gets will give you binaries (e.g. Strings). One thing you can do to check what you're receiving is using IO.inspect(salary)

It should probably produce something like

"1000\n"

So, you might need to remove the \n and then parse. You can remove by using String.replace/4

You might also need to remove any special characters included (e.g $).

Then, when you have the number itself, you can use String.to_integer/1 or String.to_float/1 to parse the number depending on if you're expecting an integer or a float value.

A basic working version could be:

defmodule M do
  def main do   
     calc()
  end

  def calc do
    salary =
      IO.gets("What is your salary?")
      |> String.trim()
      |> String.replace("\n", "")
      |> String.to_integer()

    IO.puts "Your tithe this month is: #{salary * 0.01}"
  end
end

Assuming that the numbers will always be integers. But of course, you can add more logic to account for both.

You could also use Integer.parse/2 and Float.parse instead, which might help in removing additional characters, like:

defmodule M do
  def main do   
     calc()
  end

  def calc do
    {salary, _other_chars} =
      IO.gets("What is your salary?")
      |> Float.parse()

    IO.puts "Your tithe this month is: #{salary * 0.01}"
  end
end

It might be a better, more generic function, but it will always produce a float

Upvotes: 2

Related Questions