R
R
Roman Mirilaczvili2017-10-19 15:50:19
Ruby on Rails
Roman Mirilaczvili, 2017-10-19 15:50:19

How to use BigDecimal.as_json to format the sum of BigDecimal "1.20" not in "1.2", but in "1.20"?

When an object instance is serialized using .as_json, one of the attributes of type BigDecimal(8,2) is serialized without zero, i.e. So:

> BigDecimal.new("1.20").as_json
=> "1.2"
Those. there is no final digit 0 in the price.
Trial code on the Struct example:
Price = Struct.new(:product, :money)
obj = Price.new 'квас', BigDecimal.new("1.20")
puts obj.to_json
=> {"product":"kvass","money":"1.2"}
How can I override BigDecimal.as_json so that the amount is formatted as nnn.nn?
I need to format it like this:
'%.2f' % BigDecimal.new("1.20")
Only I need to override it locally, within the same ActiveRecord model, not globally.
Rails 4.2, Ruby 2.3, gem json 1.8.3

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman Mirilaczvili, 2017-10-19
@2ord

Something I did not immediately guess about such a simple solution:

h = my_model.as_json
h[:price] = '%.2f' % my_model.price  # переопределяем результат BigDecimal.as_json с новым форматированием строки

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question