json-c: 格式化新的双对象类型?

json-c: Format new double object type?

我使用 json-c 库来创建 json 格式的字符串。我有一些浮点值,json-c 做了一些转换为双精度值,这导致了一些错误:

float nachtmodusfaktor;
nachtmodusfaktor = 0.8;

json_object_object_add(jsons[8],"nachtmodusfaktor",json_object_new_double(round(nachtmodusfaktor * 10) / 10));

json 字符串中的结果是:

     "nachtmodusfaktor": 0.80000000000000004,

我是否进行 round() 调用并不重要。在这两种情况下都有这些故障。

有没有办法告诉 json-c 库仅使用 printf(即 "%5.2f")以定义的格式放置对象,然后将显示 0.80 而不是以上?

或者您有解决方法吗?

谢谢!

/KNEBB

这正是函数 json_object_new_double_s 存在的原因:

来自 doc

Create a new json_object of type json_type_double, using the exact serialized representation of the value.

This allows for numbers that would otherwise get displayed inefficiently (e.g. 12.3 => "12.300000000000001") to be serialized with the more convenient form.

json_object_new_double(round(nachtmodusfaktor * 10) / 10); 应替换为:

   char buffer[8];
   sprintf(buffer, "%f", nachtmodusfaktor);
   json_object_new_double_s(nachtmodusfaktor, buffer);