5

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
  • 226,338
  • 43
  • 373
  • 367
Doctore
  • 61
  • 3

1 Answers1

6

Use String#%:

def book_price
  "Price: %.2f" % @price
end
ndnenkov
  • 35,425
  • 9
  • 72
  • 104