I'd like to round my floats to get rid of all trailing zeros after the decimal place in rails, inside a model method.
So, 30.0
becomes 30
but 10.5
stays 10.5
.
I know about number_with_precision and it works if I do
include ActionView::He开发者_如何学运维lpers::NumberHelper
in my model. Is this poor design? Is there a better alternative that doesn't involve moving the rounding into a helper?
This is the source code of the number_with_precision
method.
# File actionpack/lib/action_view/helpers/number_helper.rb, line 199
def number_with_delimiter(number, options = {})
options.symbolize_keys!
begin
Float(number)
rescue ArgumentError, TypeError
if options[:raise]
raise InvalidNumberError, number
else
return number
end
end
defaults = I18n.translate(:'number.format', :locale => options[:locale], :default => {})
options = options.reverse_merge(defaults)
parts = number.to_s.to_str.split('.')
parts[0].gsub!(/(\d)(?=(\d\d\d)+(?!\d))/, "\\1#{options[:delimiter]}")
parts.join(options[:separator]).html_safe
end
Nothing prevents you to clone this method into your model. You might want to remove the unnecessary parts.
精彩评论