2012-07-26 106 views
14

如何使用number_to_currency並使其在小數部分刪除零?所以如果我有一個數字30.50,我想保留.50,但如果我有30.00,我想刪除這些零。我看到的精度,但我不知道我是否可以有條件地使用它只是被應用,如果尾隨小數零...Rails:Number to currency,刪除尾隨零

感謝

回答

33
num = 30.00 
number_to_currency(num, :precision => (num.round == num) ? 0 : 2) 
    => $30 

num = 30.05 
number_to_currency(num, :precision => (num.round == num) ? 0 : 2) 
    => $30.05 
0

我用錢串,所以我做它不同的方式:

def string_to_cents str 
    new_str = number_to_currency(str, :format => "%n") 
    if new_str && new_str[-3..-1] == ".00" 
     new_str[-3..-1] = "" 
    end 
    new_str 
end