5

I have 3 string variables that I need to add. a = "5.21", b= "5.22" and c = "5.23". When I try to add i get a string, I need the numerical value

I have tried the following

a = a.to_f => 5.2
b = b.to_f => 5.2
c = c.to_f => 5.2
sum = a + b + c => 15.6

How do i get output 15.66. please help

2
  • Are you sure your a, b and c parameters are not all set to "5.2"? ... seems like the #to_f method should return a different value. Maybe the values are changed by some line of code you didn't notice...? Commented Apr 13, 2015 at 0:18
  • I suspect you have one or more invisible characters in your strings. Try this and report the result: .each_char { |c| puts c.ord }. Where did the values of a, b and c come from? Commented Apr 13, 2015 at 1:33

1 Answer 1

11

Try taking advantage of Ruby's built in Enumerable methods. Try this:

a = "5.21"
b = "5.22"
c = "5.23"

[a, b, c].map(&:to_f).inject(:+)
#=> 15.66
Sign up to request clarification or add additional context in comments.

4 Comments

i am using 2.0.0 and i am getting 15.6 using the above solution
Are you sure there's no other code modifying these variables? Also, are their values the same as the strings you gave? If there are other, non-Numeric characters in the string it can have unintended behavior. See ruby-doc.org/core-2.2.0/String.html#method-i-to_f
I am reading this value from an android app Once i read the value from the app, just to makes sure its a string i am calling the a = a.to_s.strip methods. then a = a.to_f. This still returns jus 5.0 although in this case the string was 5.00
Try printing a at each step in the process, including before you call to_s.strip on the number. If at some point you start seeing a with only one number after the decimal, you know the previous operation cut it off. Let me know what happens.

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.