I am aware of number_to_currency, but wanted to use number_with_precision to output a price for some products in a db

I have a prices stored in a db, which has column type decimal precision: 10, scale: 2. The prices are stored as 3.00 and 2.99

I have a problem outputting the prices - it outputs correctly for the 2.99 price, but only outputs 3.0 for the other

Do you have any information on how to get all numbers to show two decimal places regardless of their value?

Thanks!

Here is my code:

#app/models/feature.rb
def price=(price)
    number_with_precision price
end
有帮助吗?

解决方案 2

You specify the number of digits after decimal in the precision option:

<%= number_with_precision(price, precision: 2) %>

number_with_precision is from ActionView::Helpers::NumberHelper module. To use it where you don't have this helper available, you need to include this module:

class MyClass
  include ActionView::Helpers::NumberHelper

  def price_to_number(price)
    number_with_precision(price, precision: 2)
  end
end

其他提示

There's really not a need for a more complicated method to do this in your case. Just use Ruby:

'%.2f' % price
# e.g:
'%.2f' % 3 #=> "3.00"

The answer was thus:

#app/models/feature.rb
class Feature < ActiveRecord::Base
  include ActionView::Helpers::NumberHelper

  def price
     number_with_precision read_attribute(:price), precision: 2
  end
end
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top