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

Andrew Stelmach
12,583 PointsExtra Credit: multiply two numbers and display the answer as a number with two decimal places
How do you get Ruby to change a Fixnum, or a Float, (or even a String?) into a number with two decimal places.
I'm thinking of converting the number into currency, but this feels like cheating.
3 Answers

Maciej Czuchnowski
36,441 PointsOne way of doing this is by using the round method like this:
number.round(2)
The problem is, if you have a number like 1.999876, it will return 2.0, so it's not always what you expect.
The other way I know looks like it was taken from C programming language:
sprintf('%.2f', number)
Assuming it's a float, if it's anything else, you have to change the f
to something else. Non-floats (also strings) can be changed into a float like this:
number.to_f

Andrew Stelmach
12,583 PointsThanks! That helped a lot. It worked. My code:
puts "Enter your first number:"
number1 = gets.to_f
puts "Enter the second number (to be multiplied by your first):"
number2 = gets.to_f
answer = sprintf('%.2f', number1*number2)
puts "These two numbers multiplied together = #{answer}"

Jeffery Briggette
Courses Plus Student 5,567 PointsThe to_f method won't make any difference, since the sprintf function will add the 2 decimal places regardless whether or not the number variables are a float or a fixnum. You can just as easily have the .to_i method. The outcome will be the same. Just a little tid-bit.

Maciej Czuchnowski
36,441 PointsOK, try and run Andrew's code with to_f's changed to to_i and try it for numbers 2.99 and 1. The result will be 2.00, which is not what we want, so to_f is actually required here :). We use sprintf to only SHOW 2 decimal places in case the user enters more or the result would have more than two.

Jeffery Briggette
Courses Plus Student 5,567 PointsOK. I see what you are saying. Didn't think of someone multiplying floats. So .to_f will pretty much cover all our bases. I get it. Thank you for your input.