#include <iostream>
#include <string>
#include <limits>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
int main()
{
std::cout.precision(std::numeric_limits<double>::max_digits10);
// create a JSON value with different types
json json_types =
{
{"number_b", 1234567890.0123456789}
};
std::cout << std::fixed << json_types.dump(4) << std::endl;
auto v2 = json_types["number_b"].get<double>();
std::cout << "number_b in double: " << std::fixed << v2 << std::endl;
// auto v3 = json_types["number_b"].get<std::string>();
// [json.exception.type_error.302] type must be string, but is number
}
Output:
{
"number_b": 1234567890.0123458
}
number_b in double: 1234567890.01234579086303711
Is there a way that I can get the value of number_b
as a std::string
based on the original input value of "1234567890.0123456789"
?
Note: the JSON number value is passed in through a third-party and I cannot change the input value from a number to a string from the source.
A
double
has about 15-17 decimal places of precision [1]. Adouble
cannot store1234567890.0123456789
exactly and thus you will not be able to convert it to the exact string, if it is stored into adouble
first.You can try to hook on the sax interface [2], that the nlohmann library provides (more specifically the
number_float()
) function to get the original string, that was present in the json during parsing.I would however not rely on such hacks. Working with floating point numbers is inherently not exact and it is probably better to just look if the number is in a small range or something similar. This however depends on the exact problem that your are trying to solve.