How can I use number_to_currency
and make it delete the zeros in the decimal part?
如何使用number_to_currency并删除小数部分中的零?
So if I have a number 30.50, I want to keep the .50, but if I have 30.00, I want to delete those zeros. I see the precision, but I don't know if I can use it conditionally to just be applied if the trailing decimals are zeros...
所以,如果我有一个30.50的数字,我想保留.50,但如果我有30.00,我想删除那些零。我看到精度,但我不知道如果尾随小数为零,我是否可以有条件地使用它...
Thanks
谢谢
2 个解决方案
#1
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
#2
0
I use money strings , so I do it a different way :
我使用金钱字符串,所以我采用不同的方式:
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
#1
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
#2
0
I use money strings , so I do it a different way :
我使用金钱字符串,所以我采用不同的方式:
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