I am trying out the eval function with a simple example:
<% a = 5 %>
<% b = 4 %>
<%= eval("((a+b)/b)") %>
I want the result to be 2.25, but the above gives 2. The code below gives 2.25 but is not very elegant
<% a = 5 %>
<% b = 4 %>
<%= eval("((a.to_f+b.to_f)/b.to_f)") %>
How can I make eval return a number with decimal places in a better way?
All you need is the denominator of the division to be floating point and Ruby will understand to use floating point arithmetic on the expression instead of the default integer arithmetic:
Edit
To further clarify – It actually has nothing to do with
evalin itself. It’s just the way Ruby (and most other languages) handle arithmetic expressions. Most expressions are done with integer arithmetic by default.When doing division in Ruby all you need is either dividend or divisor to be float to trigger floating point arithmetic.