C ++中的Json:将数字解析为字符串以避免浮点不准确

问题描述 投票:1回答:3

我正在处理加密货币RPC并接收json数据,如下所示:

{
  ...
  "amount": 1.34000000,
  "confirmations": 230016,
  "spendable": true,
  "solvable": true
  ...
}

使用Jsoncpp库或json11将数字解析为double。发生这种情况时,结果是:1.3400000000000001,由于双精度问题。总的来说,这对金融交易来说是灾难性的,是不可接受的。

我已经有一个定点库,它可以获取一个有效的字符串并在内部将其视为一个整数。有没有办法让Jsoncpp(或任何其他json库)将选定的数字json值作为字符串,这样我可以用固定精度正确对待它们?

c++ json double fixed-point jsoncpp
3个回答
1
投票

在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\"");
    };

现在它正常工作。


0
投票

我喜欢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

-1
投票

原生jsoncpp解决方案是RTFM! (例如,这里:https://open-source-parsers.github.io/jsoncpp-docs/doxygen/class_json_1_1_stream_writer_builder.html

Json::StreamWriterBuilder builder;
builder["commentStyle"] = "None";
builder["indentation"] = "   ";
builder["precision"] = 15;

这将设置您的编写器浮点精度,以避免在双重表示中打印小截断错误。例如,而不是json字段,

“金额”:1.3400000000000001,

你现在会得到

“金额”:1.340000000000000,

如预期的。

© www.soinside.com 2019 - 2024. All rights reserved.