其他分享
首页 > 其他分享> > c – 使用rapidjson设置浮点精度

c – 使用rapidjson设置浮点精度

作者:互联网

有没有办法控制使用rapidjson生成的JSON中的输出精度?

例如:

writer.String("length");
writer.Double(1.0 / 3.0);

这会产生类似于:

{ length: 0.33333333 }

我发送了很多值,只需要两个小数位就可以得到几个值.

解决方法:

从消息来源

Writer& Double(double d)
{ 
   Prefix(kNumberType);
   WriteDouble(d);
   return *this; 
}

//! \todo Optimization with custom double-to-string converter.
void WriteDouble(double d) {
        char buffer[100];
#if _MSC_VER
    int ret = sprintf_s(buffer, sizeof(buffer), "%g", d);
#else
    int ret = snprintf(buffer, sizeof(buffer), "%g", d);
#endif
    RAPIDJSON_ASSERT(ret >= 1);
    for (int i = 0; i < ret; i++)
         stream_.Put(buffer[i]);
}

For the g conversion style conversion with style e or f will be
performed.

f: Precision specifies the minimum number of digits to appear after
the decimal point character. The default precision is 6.

引自here

有变种,编写新的Writer类并编写自己的Double函数实现.

最后一个案例的简单例子

template<typename Stream>
class Writer : public rapidjson::Writer<Stream>
{
public:
   Writer(Stream& stream) : rapidjson::Writer<Stream>(stream)
   {
   }
   Writer& Double(double d)
   {
      this->Prefix(rapidjson::kNumberType);
      char buffer[100];
      int ret = snprintf(buffer, sizeof(buffer), "%.2f", d);
      RAPIDJSON_ASSERT(ret >= 1);
      for (int i = 0; i < ret; ++i)
         this->stream_.Put(buffer[i]);
      return *this;
   }
};

用法如

int main()
{
   const std::string json =
      "{"
      "\"string\": 0.3221"
      "}";
   rapidjson::Document doc;
   doc.Parse<0>(json.c_str());

   rapidjson::FileStream fs(stdout);
   Writer<rapidjson::FileStream> writer(fs);
   doc.Accept(writer);
}

结果:{“string”:0.32}

当然如果您手动使用Writer,您可以使用精度参数编写函数Double.

标签:c,json,rapidjson
来源: https://codeday.me/bug/20190825/1722420.html