2016-07-28 93 views
0

这里非常简单的语法问题,因为我是新来的铁轨。在我的控制器中,我有两个变量,我试图在重定向后显示在通知中。他们是piece.title和piece.price(片是我的模型)。价格是一个小数,所以我想用小数点后两位数字(如<%= number_with_precision piece.price, :precision => 2 %>显示它注意与变量和数字精度

我当前的代码是:

redirect_to pieces_path, notice: "Thanks for buying #{piece.title} for #{piece.price}." 

这工作,但我如何得到的价格两位小数?当我尝试做的数量与精确度,我得到的语法错误。

感谢。

回答

0

您可以使用此实现它:

'%.2f' % 10 
#=> "10.00" 

"Thanks for buying #{piece.title} for #{'%.2f' % price}." 
#=> "Thanks for buying Coffee for 10.00." 

您的通知改成这样

class YourControllerName 
    def my_method 
    #...... 
    redirect_to pieces_path, notice: "Thanks for buying #{piece.title} for #{'%.2f' % piece.price}." 
    end 
end 
0

什么错误,你好吗?我的猜测是price.piece是零,因为你的代码看起来是正确的,假设你是在你看来使用它而不是你的控制器。此外,如果它应该是钱,你应该使用number_to_currency

<%= number_to_currency piece.price, :precision => 2 %> 
+0

菲利普,这是在我的控制器中。代码在我的问题没有erros,但我想显示的价格小数点后两位。我试图使用<%= %>标签,但它没有在控制器中识别它们。你知道如何解决这个问题吗? –