当浮点数

时间:2018-03-14 04:13:42

标签: ruby rounding

即使尾随数字为0,如何在浮点数上显示2个小数位(填充)。因此,如果我只对下面示例中的:cost值求和,我希望它返回23.00

items = [
    {customer: "John", item: "Soup", cost:("%.2f"% 8.50)}, 
    {customer: "Sarah", item: "Pasta", cost:("%.2f"% 12.00)}, 
    {customer: "John", item: "Coke", cost:("%.2f" % 2.50)}
]

问题: 我成功显示成本:两位小数的值。但是,结果返回“字符串”。我已经尝试了 (“%。2f”%2.50).to_f 而没有这样的运气。我需要一个浮点数,以便我可以完成以下注入代码。

totalcost = items.inject(0) {|sum, hash| sum + hash[:cost]}

puts totalcost

当运行此总和时,我收到以下错误的总成本,因为我无法成功将字符串转换为浮点数。 字符串无法强制转换为Integer(TypeError)

2 个答案:

答案 0 :(得分:1)

您可以在将其转换为数字(整数/浮点数)后计算成本值的总和。

totalcost  = items.map { |x| x[:cost].to_f }.sum

totalcost的值可以用sprintf method格式化,无论我们想要显示什么。

sprintf("%.2f", totalcost)

希望它有所帮助!

答案 1 :(得分:0)

hash [:cost]仍然返回一个String。您可以在将其添加到总和之前将其覆盖到浮点数

totalcost = items.inject(0) {|sum, hash| sum + hash[:cost].to_f}
相关问题