4

Please, consider the following code:

class Book
  def initialize (price)
   @price=price
  end

  def book_price
   puts "Price: #{@price}"
  end
end

book1=Book.new(19.60)
book1.book_price

It always returns "Price:19.6" instead of "Price:19.60"

I have tried changing @price=price.to_f, but it made no difference. How can I keep the trailing zero without converting to string?

Sergio Tulentsev
  • 219,187
  • 42
  • 361
  • 354
Doctore
  • 51
  • 3

1 Answers1

5

Use String#%:

def book_price
  "Price: %.2f" % @price
end
ndnenkov
  • 34,386
  • 9
  • 72
  • 100