include ActionView::Helpers::NumberHelper
def per_item_cost
number_with_precision(read_attribute(:per_item_cost), precision: 2)
end
How to always format a value coming out as two decimal spaces in Rails
-
06-07-2023 - |
Question
I am using Rails 3.2.17 and am storing prices for items like this (an example migration):
add_column :item_counts, :per_item_cost, :decimal, :precision => 8, :scale => 2
but if it's 23.00, it comes out as 23.0. I tend to create a method like this:
def helpers
ActionController::Base.helpers
end
def per_item_cost_formatted
helpers.number_to_currency(per_item_cost, precision: 2, format: "%n")
end
Is there a way I can specify that it always outputs formatted to be 23.00? Something like:
def per_item_cost
helpers.number_to_currency(per_item_cost, precision: 2, format: "%n")
end
causes an endless loop.
Solution
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow