Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby Ruby Foundations Numbers Random Numbers and Formatting

alexandermuhr
alexandermuhr
3,466 Points

Extra Credit for Number Formatting (Ruby)

So I am trying to do the extra credit from this section... any ideas what I am doing wrong? I do the exact same sequence in irb, and it seems to run correctly, but not when I run the program.

print "Enter a dollar amount: "
dollar_1 = gets
print "Enter another dollar amount: "
dollar_2 = gets
total = dollar_1.to_f * dollar_2.to_f
puts = "#{total}\n"

1 Answer

Hi Alex!

The answer to your question is twofold, but I will give you a couple of hints and hopefully you will be able to make it work.

Hints:

Hint 1: Go to the Ruby documentation and on the the very top of the page it gives you sprintf function which will transform a float to a string with the ability to determine the floating point.

sprintf "%.1f", 1.234    #=> "1.2"

Hint 2: Figure out how to make the input for dollar1 and dollar2 a number (e.g. a floating number) instead of a string before you do the calculation on it, as it is not possible to do multiplication on a string in the way that you would assume otherwise.

I hope that helps!

alexandermuhr
alexandermuhr
3,466 Points

I understand the print portion... but I am struggling with finding how to convert the string to a float. Why does it not work with the way I did it? If I convert using to_f before the "total" equation, it doesn't save as a float... so how do I use the bang(!) method to make sure my string stays a float?

Try taking the input values in as a float first (e.g. dollar1 = gets.to_f) then do the multiplication on them. It doesn't work because you haven't specified what the input type should be.

No problem! Thank you for asking!