Ruby / Rails:剥离无效的零,但只有0或2

时间:2014-03-14 23:02:42

标签: ruby-on-rails ruby

我想在我的rails项目中显示价格。我知道我有number_to_currencynumber_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"

我该怎么做?

2 个答案:

答案 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#sprintfFloat#===

@sawa使用String#%方法提出的另一个很好的建议:

val = (num.to_i == num ? "%d" : "%.2f") % num