代码之家  ›  专栏  ›  技术社区  ›  Jake Metz

当浮点中有尾随的0时,如何显示2位小数

  •  1
  • Jake Metz  · 技术社区  · 7 年前

    即使尾随数字是0,如何在浮点上显示2位小数(填充)。因此,如果我只对以下示例中的:成本值求和,我希望它返回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)。至\u f 没有这样的运气。我需要一个float,以便完成以下注入代码。

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

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

    2 回复  |  直到 7 年前
        1
  •  4
  •   Ashik Salman    7 年前

    将成本值转换为数字(整数/浮点)后,可以计算成本值之和。

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

    的价值 totalcost 可以用 sprintf method 无论我们想以何种方式展示。

    sprintf("%.2f", totalcost)
    

    希望有帮助!

        2
  •  0
  •   Shani    7 年前

    哈希[:cost]仍然返回字符串。您可以在将其添加到总和之前将其覆盖到浮动中

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