我正在处理加密货币RPC并接收json数据,如下所示:
{
...
"amount": 1.34000000,
"confirmations": 230016,
"spendable": true,
"solvable": true
...
}使用约翰西普库或json11获取解析为double的数字。当发生这种情况时,结果是:1.3400000000000001,由于双精度问题。总的来说,这对金融交易是灾难性的,是不可接受的。
我已经有了一个定点库,它可以接受一个有效的字符串,并在内部将它作为一个整数来处理。有没有一种方法可以让Jsoncpp (或任何其他json库)将选定的数字json值作为字符串,这样我就可以以固定的精度对待它们了吗?
发布于 2018-06-28 20:42:34
在json库中似乎没有解决方案,所以我不得不自己修改数字并用引号包装它。我把这个函数应用到响应中去。
[](std::string& jsonStr) {
// matches "amount" field in json
static std::regex reg(R"((\s*\"amount\"\s*:)\s*(\d*\.{0,1}\d{0,8})\s*)");
jsonStr = std::regex_replace(jsonStr, reg, "$1\"$2\"");
};现在它正常工作了。
发布于 2018-07-11 08:14:51
我喜欢ThorsSerializer。免责声明我写的。
它支持你正在寻找的东西。
您可以告诉解析器对一个类使用标准的输入/输出操作符(然后您可以自己定义)。
示例:
#include "ThorSerialize/JsonThor.h"
#include "ThorSerialize/SerUtil.h"
#include <sstream>
#include <iostream>
#include <string>
#include <map>
struct FixedPoint
{
int integerPart;
int floatPart;
friend std::istream& operator>>(std::istream& stream, FixedPoint& data)
{
// This code assumes <number>.<number>
// Change to suite your needs.
char c;
stream >> data.integerPart >> c >> data.floatPart;
if (c != '.')
{
stream.setstate(std::ios::failbit);
}
return stream;
}
};
// This declaration tells the serializer to use operator>> for reading
// and operator<< for writing this value.
// Note: The value must still conform to standard Json type
// true/false/null/integer/real/quoted string
ThorsAnvil_MakeTraitCustom(FixedPoint);
struct BitCoin
{
FixedPoint amount;
int confirmations;
bool spendable;
bool solvable;
};
// This declaration tells the serializer to use the standard
// built in operators for a struct and serialize the listed members.
// There are built in operations for all built in types and std::Types
ThorsAnvil_MakeTrait(BitCoin, amount, confirmations, spendable, solvable);示例用法:
int main()
{
using ThorsAnvil::Serialize::jsonImport;
using ThorsAnvil::Serialize::jsonExport;
std::stringstream file(R"(
{
"amount": 1.34000000,
"confirmations": 230016,
"spendable": true,
"solvable": true
}
)");
BitCoin coin;
file >> jsonImport(coin);
std::cout << coin.amount.integerPart << " . " << coin.amount.floatPart << "\n";
}内部版本:
> g++ -std=c++1z 51087868.cpp -lThorSerialize17发布于 2019-03-11 06:53:31
本地的jsoncpp解决方案是RTFM!(例如,此处:builder.html)
Json::StreamWriterBuilder builder;
builder["commentStyle"] = "None";
builder["indentation"] = " ";
builder["precision"] = 15;这将设置写入器浮动精度,以避免在双重表示中打印小的截断错误。例如,代替json字段,
“金额”:1.340000000000000001,
你现在会得到
“金额”:1.3400000000000000,
如你所愿。
https://stackoverflow.com/questions/51087868
复制相似问题