michalmuskala / jason

A blazing fast JSON parser and generator in pure Elixir.
Other
1.58k stars 168 forks source link

Change behaviour of Float #176

Closed neel-desh closed 8 months ago

neel-desh commented 8 months ago

Hi, I just wanted to know how do I change the behavior of Float in Jason.encode!()

By default Jason.encode!(1000.0) returns "1.0e3" I want Jason.encode!(1000.0) to return "1000.0"

I tried to make this change.

  defimpl Jason.Encoder, for: Float do
    def encode!(float, _opts) do
      :erlang.float_to_binary(float, [{:decimals, 15}, :compact])
    end
  end

And I was expecting it to work! but sadly it did not. Can someone please guide me in the right direction.

Thanks

michalmuskala commented 8 months ago

In general overriding protocol implementations is not supported in Elixir and is largely accidental how it would work. For Jason in particular, it does not use the protocol for encoding core data types to avoid the overhead of the protocol dispatch in the regular case. This means there is generally no way to override how values are encoded, other than: