[英]Controlling the number of significant digits used by jsonencode
I'd like to use jsonencode in Matlab R2022a to encode a structure containing double precision values, like eg:我想在 Matlab R2022a 中使用jsonencode来编码包含双精度值的结构,例如:
>> 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:但我不需要所有数字,我想保持 JSON 文件简短,所以我想要一个 output,例如:
'{"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. jsonencode
中似乎没有这样的选项,所以我试图事先删除不太重要的数字。 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.这些错误不会一直发生,但似乎struct
越深,我出现这些舍入错误的频率就越高。
Then I have tried to use vpa , but it does not seem to be compatible with jsonencode
:然后我尝试使用vpa ,但它似乎与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?是否有可能获得一个干净的 JSON output 并使用纯 Matlab 控制有效数字?
I changed the way I round numbers by using a feature of the round
function and it removed the random rounding approximations (probably due to the division by the power of 10):我通过使用 function round
的特征改变了我舍入数字的方式,它删除了随机舍入近似值(可能是由于除以 10 的幂):
>> s.a = round(s.a, 4, 'significant')
s =
struct with fields:
a: 1.414
>> jsonencode(s)
ans =
'{"a":1.414}'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.