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

时间:2017-02-23 17:44:04

标签: 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)

  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

我感谢任何帮助!

1 个答案:

答案 0 :(得分:1)

你可以这样做:

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