I have a BigDecimal that has either 0, 1 or 2 decimal digits (I'm calling round(2) on it). I want to display it in a view in such a way that it'll only show as many decimal digits as needed. In other words:
我有一个BigDecimal,它有0,1或2个十进制数字(我在它上面调用round(2))。我希望在视图中以这样的方式显示它,它只会显示所需的十进制数字。换一种说法:
7.0 -> "7"
7.5 -> "7.5"
7.67 -> "7.67"
How do I achieve this? So far, it's showing "7.0" instead of "7".
我该如何实现这一目标?到目前为止,它显示的是“7.0”而不是“7”。
2 个解决方案
#1
12
For your views, look at the methods from the NumberHelper, in particular the number_with_precision
, http://api.rubyonrails.org/classes/ActionView/Helpers/NumberHelper.html#method-i-number_with_precision
对于您的视图,请查看NumberHelper中的方法,特别是number_with_precision,http://api.rubyonrails.org/classes/ActionView/Helpers/NumberHelper.html#method-i-number_with_precision
Particularly, you want the strip_insignificant_zeros option.
特别是,您需要strip_insignificant_zeros选项。
#2
9
You don't need Ruby on Rails when you have the geeky magic of sprintf
:
当你拥有sprintf的令人讨厌的魔力时,你不需要Ruby on Rails:
[7.0, 7.5, 7.57].map{ |f| "%g" % BigDecimal.new(f,3) }
#=> ["7", "7.5", "7.57"]
#1
12
For your views, look at the methods from the NumberHelper, in particular the number_with_precision
, http://api.rubyonrails.org/classes/ActionView/Helpers/NumberHelper.html#method-i-number_with_precision
对于您的视图,请查看NumberHelper中的方法,特别是number_with_precision,http://api.rubyonrails.org/classes/ActionView/Helpers/NumberHelper.html#method-i-number_with_precision
Particularly, you want the strip_insignificant_zeros option.
特别是,您需要strip_insignificant_zeros选项。
#2
9
You don't need Ruby on Rails when you have the geeky magic of sprintf
:
当你拥有sprintf的令人讨厌的魔力时,你不需要Ruby on Rails:
[7.0, 7.5, 7.57].map{ |f| "%g" % BigDecimal.new(f,3) }
#=> ["7", "7.5", "7.57"]