问题描述
有没有一种方法可以控制使用RapidJSON生成的JSON中的输出精度?
Is there a way to control the output precision in JSON generated using rapidjson?
例如:
writer.String("length");
writer.Double(1.0 / 3.0);
这会生成类似以下内容的
This generates something like:
{ length: 0.33333333 }
我要发送很多值,几个值只需要小数点后两位.
I'm sending a lot of values and only need two decimal places for several values.
推荐答案
来源
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]);
}
f
:精度指定出现在后面的最小位数 小数点字符.默认精度为6
.
f
: Precision specifies the minimum number of digits to appear after the decimal point character. The default precision is 6
.
有一个变体,可以编写新的Writer
类并编写自己的Double
函数实现.
There is variant, to write new Writer
class and write your own Double
function realisation.
最后一种情况的简单示例
Simple example of last case
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}
result: {"string":0.32}
当然,如果您手动使用Writer
,则可以使用精度参数编写函数Double
.
Of course if you use Writer
manually, you can writer function Double
with precision parameter.
这篇关于使用RapidJSON设置浮点精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!