Reputation: 465
I would like to know how to get rails to render in json a bigdecimal as a number without a trailing zero.
Currently in my app, using as_json
Rails renders a bigdecimal value of an active record entity as a number with a decimal, e.g. bigdecimal 2.0 is rendered 2.0 (not a string). I want it to be rendered as 2 (not a string, without trailing zero).
To attempt this, I have made use of jbuilder and used the rails helper method number_with_precision
and option strip_insignificant_zeros: true
; however, this converts the value to a string. Tacking on to_f
to the end makes '2' 2.0.
Is there a way to render in json a bigdecimal as a number without trailing zeros?
Thank you
Upvotes: 1
Views: 1010
Reputation: 1407
If fractional part of the number is 0 - just convert to Integer, otherwise convert to Float.
(x.frac.zero? ? x.to_i : x.to_f)
Upvotes: 1