Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JSON.jl Float64 serialization (suppress scientific notation) #367

Open
tamasgal opened this issue Sep 24, 2024 · 0 comments
Open

JSON.jl Float64 serialization (suppress scientific notation) #367

tamasgal opened this issue Sep 24, 2024 · 0 comments

Comments

@tamasgal
Copy link

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 ;) I am reposting it from Discourse since I feel like it's a too specific question and might be better discussed here.

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\""

Where should I intercept the scientific notation for large floats without being a pirate? 🏴‍☠️

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant