Search code examples
c++jsondoublefixed-pointjsoncpp

Json in C++: Parse a number as a string to avoid floating-point inaccuracy


I'm dealing with a cryptocurrency RPC and receiving json data as follows:

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

Using Jsoncpp library or json11 gets the number parsed to a double. When this happens, the result is: 1.3400000000000001, due to double accuracy problems. In general this is catastrophic to financial transations and unacceptable.

I already have a fixed-point library that can take a valid string and treat it as an integer internally. Is there a way I could make Jsoncpp (or any other json library) take selected numeric json values as strings, so that I could treat them the right way with fixed-precision?


Solution

  • There doesn't seem to be a solution in json libraries, so I had to modify the number myself and wrap it with quotes. I applied this function to the responses to do that.

    [](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\"");
        };
    

    And now it works properly.