I'd like to use jsonencode in Matlab R2022a to encode a structure containing double precision values, like e.g.:
>> s = struct('a', sqrt(2))
s =
struct with fields:
a: 1.4142
>> jsonencode(s)
ans =
'{"a":1.4142135623730951}'
But I don't need all the digits and I'd like to keep the JSON file short, so I'd like to have an output like:
'{"a":1.414}'
There does not seem to have such an option in jsonencode
, so I have tried to remove the less significant digits beforehand. Unfortunately there are random rounding errors:
>> s.a = round(s.a*10^3)*10^-3
s =
struct with fields:
a: 1.4140
>> jsonencode(s)
ans =
'{"a":1.4140000000000005}'
These errors do not occur all the time, but it seems that the deeper the struct
the more often I have these rounding errors.
Then I have tried to use vpa, but it does not seem to be compatible with jsonencode
:
>> s.a = vpa(s.a,4)
s =
struct with fields:
a: 1.414
>> jsonencode(s)
ans =
'{"a":{}}'
Now I'm out of options. Is it possible to get a clean JSON output with control over the significant digits using pure Matlab ?