Answer the question
In order to leave comments, you need to log in
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. Price = Struct.new(:product, :money)
obj = Price.new 'квас', BigDecimal.new("1.20")
puts obj.to_json
=> {"product":"kvass","money":"1.2"} Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question