Ruby 显示两个小数而不与方法冲突

Ruby 显示两个小数而不与方法冲突,ruby,methods,Ruby,Methods,我试图转换用户给出的数字输出,使其始终显示2位小数。我知道“%.2f%”存在,但它总是显示此错误字符串,无法强制转换为fixnum。我认为它与方法冲突 这是我的密码: hash = {} entry = " " while entry != "q" print "Enter your item: " item = gets.chomp print "Enter the associated cost: " cost = gets.chomp.to_f.round(2)

我试图转换用户给出的数字输出,使其始终显示2位小数。我知道“%.2f%”存在,但它总是显示此错误字符串,无法强制转换为fixnum。我认为它与方法冲突

这是我的密码:

hash = {}
entry = " "

 while entry != "q"
  print "Enter your item: "
  item = gets.chomp

  print "Enter the associated cost: "
  cost = gets.chomp.to_f.round(2)

  print "Press any key to continue or 'q' to quit: "
  entry = gets.chomp


hash[item] = cost

end

puts "Receipt: "
puts "----------"

hash.each do |k,v|
puts "#{k} => $#{v}"

end

puts "----------"

print "subtotal: "

subtotal = hash.values.inject(0, :+)


print "$"
puts  '%.2f' % subtotal.round(2)

print "tax: $"
tax = subtotal * 0.06 
puts '%.2f' % tax.round(2)

print "total: $"
total = subtotal + tax
puts  '%.2f' % total.round(2)
所以基本上这一步:

hash.each do |k,v|
puts "#{k} => $#{v}"
例如,当我在一个步骤中输入一个成本为1时,它将显示为

1.0美元,而不是1.00美元

谢谢你的帮助

您可以执行以下操作:

hash.each do |k,v|
  puts "#{k} => $#{'%.2f' % v}"
end

非常感谢。工作得很好@太好了,祝你编码顺利。