JSON.jl Float64 serialization (suppress scientific notation)

I am having a hard time with JSON.jl. I want to serialize large Float64 instances without scientific notation and the only way I was able to get at least the rounding working results in a string, instead of a float value :wink:

using Printf
using JSON
import JSON.Serializations: CommonSerialization, StandardSerialization
import JSON.Writer: StructuralContext, show_json

struct RoundedFloatSerialization <: CommonSerialization end

show_json(io::StructuralContext,
            ::RoundedFloatSerialization,
           f::AbstractFloat) =
    show_json(io, StandardSerialization(), @sprintf("%.3f", f))

Here is an example which shows that 1e4 is serialized to 10000.0 by default, whereas 1e9 to 1.0e9. The hook into the show_json works, but it yields a String for obvious reasons, see below an example.

julia> JSON.json(1e4)
"10000.0"

julia> JSON.json(1e9)
"1.0e9"

julia> sprint(show_json, RoundedFloatSerialization(), 1e4)
"\"10000.000\""

julia> sprint(show_json, RoundedFloatSerialization(), 1e9)
"\"1000000000.000\""

I think I might be on the wrong path and I am pretty sure it’s a fairly common question but wondering at the same time why I don’t find any existing posts about it :laughing:

Where should I intercept the scientific notation for large floats without being a pirate? :pirate_flag:

Update: follow-up here JSON.jl Float64 serialization (suppress scientific notation) · Issue #367 · JuliaIO/JSON.jl · GitHub

1 Like