我想在我的rails项目中显示价格。我知道我有number_to_currency
和number_with_precision
方法可以帮助我。
尽管如此,我找不到以优雅的方式实现我想要的方法。
display_price(50) # => "50"
display_price(50.5) # => "50.50" this is the one I can't achieve ...
display_price(50.50) # => "50.50"
display_price(50.55) # => "50.55"
display_price(50.551) # => "50.55"
我该怎么做?
答案 0 :(得分:5)
使用正则表达式删除.00
:
number_with_precision(50, precision: 2).sub(/\.00$/,'') # => "50"
number_with_precision(50.5, precision: 2).sub(/\.00$/,'') # => "50.50"
非铁路方式:
("%0.02f" % 50.5).sub(/\.00$/,'')
答案 1 :(得分:1)
以下是我的工作方式:
num = 50.5
val = Float === num ? sprintf("%.2f",num) : sprintf("%d",num)
val # => "50.50"
num = 50.551
val = Float === num ? sprintf("%.2f",num) : sprintf("%d",num)
val # => "50.55"
num = 50
val = Float === num ? sprintf("%.2f",num) : sprintf("%d",num)
val # => "50"
您需要查看方法Kernel#sprintf
和Float#===
。
val = (num.to_i == num ? "%d" : "%.2f") % num