JSON3 - How write(serialize) the specified number of significant digits?

Hi all,
I would like write short form number of digits. e.g as round(x; sigdigits=10)
I parse vector of float with help JSON3 to json string and vice versa.
Default Float64 is NumberType JSON3.StructType(::Type{<:Float64}) = JSON3.NumberType()
Any suggestions? Thx

NOTE: This is just part of the structure.

You could round the values in place. It’s a little bit strange to have an option to change what values are serialize. Like if there was an option to apply a transform to each key before writing it out. If you’re going to do that, just transform the keys and then save the JSON.

1 Like

I’m not sure you should get into the habit of doing that, or with digits=2 (what I’m guessing is what you rather want). [For numerical applications you want all the accuracy of your calculations saved.]

Is your problem that you should rather be using:

https://github.com/JuliaMath/DecFP.jl (there’s also a slower Julia-only decimal float format library). I.e. https://en.wikipedia.org/wiki/Decimal64_floating-point_format

thus avoiding problems you see in the docs:

  If the digits keyword argument is provided, it rounds to the specified number of digits after the decimal place (or before if negative), in base base.

  If the sigdigits keyword argument is provided, it rounds to the specified number of significant digits, in base base.
  │  Rounding to specified digits in bases other than 2 can be inexact when operating on binary floating point numbers. For example, the Float64 value
  │  represented by 1.15 is actually less than 1.15, yet will be rounded to 1.2.
  │  Examples
  │  ≡≡≡≡≡≡≡≡≡≡
  │  x = 1.15
  │  1.15
  │  @sprintf "%.20f" x
  │  "1.14999999999999991118"
  │  x < 115//100
  │  true

Some trivia, Douglas Crockford who popularized the data format JSON format proposed one other format (Julia doesn’t support, but no problem as it never caught on)

Thanks, guys @StefanKarpinski & @Palli for a quick response and recommendations. I found a mistake with constructor obj[:w] ./ sum(obj[:w]) where GMMmodel expects exactly 1.0 and the SHA256 signature did not fit. Sorry :smiley: I also applied round in the constructor of a struct.

However, I have a new problem with valid writing a vector or value using serialization (method JSON3.write). I would expect to write the vector as a valid JSON format (and a simple format for other parsers). For e.g vector Foo([2.3, 4.5, NaN], NaN) as

{ “a”: [2.3, 4.5, null ], “b”: null} #This is expected :slight_smile:

As I mentioned in the link. Some suggestions for (de)serialize?

I tried to choose a number as a string.

JSON3.StructType(::Type{<:Float64}) = JSON3.StringType()

but I’ll just get only this {"a": ["2.3", "4.5", "null" ], "b": "null"} :frowning: duplicate quotes :roll_eyes: