Decimal received as {coef: 23652, exp: 0, sign: 1} at JS frontend (VueJS)

I am having a strange issue. Using Poison I encode object properties as JSON and send them to the VueJS front-end. One of the properties is a decimal field. The value is read by VueJS as something like: {coef: 23652, exp: 0, sign: 1}. How to send the decimal from the server to the front-end as a normal decimal (string like e.g. 342.23)

That is the standard encoding of the internal representation for Decimal.

For a different encoding implement a struct specific encoder.


https://blog.enuma.io/update/2019/01/31/safe-use-of-bignumber.js.html


(string like e.g. 342.23 )

If that is represented as %Decimal{coef: 34223, exp: -2, sign: 1} and you are using BigNumber.js then "34223e-2" may be the preferable approach.

4 Likes

@peerreynders

Thank you. I have tried to use the above mentioned JS libraries and others but provided the Elixir’s values for coef, exp and sign, the JS libraries produce different results.

I have tried to encode Elixir-side the decimal as string by:

defimpl Poison.Encoder, for: Acrosap.Orders.Order do
  def encode(%{doctotal: doctotal}, options) do
    Poison.Encoder.BitString.encode("#{to_string(doctotal)}", options)
  end
end

But nothing happens (still sent to front-end as decimal object). What might be wrong with my code? Thank you.

UPDATE

I was able to convert the decimal to string before sending the response to the front-end by:

defimpl Poison.Encoder, for: Decimal do
  def encode(decimal, options) do
     Decimal.to_string(decimal, :normal)
    |> Poison.Encoder.encode(options)
  end
end

I tried to do the same with the Jason library but for some reason, it doesn’t work.

4 Likes