Skip to content

Commit

Permalink
feat: floating point precision
Browse files Browse the repository at this point in the history
  • Loading branch information
neko-para committed May 14, 2024
1 parent 8438684 commit 4607356
Show file tree
Hide file tree
Showing 4 changed files with 43 additions and 0 deletions.
18 changes: 18 additions & 0 deletions include/common/utils.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@

#pragma once

#include <iomanip>
#include <limits>
#include <sstream>
#include <string>
#include <type_traits>

Expand Down Expand Up @@ -233,6 +236,21 @@ inline constexpr string_t null_string()
template <typename string_t, typename any_t>
inline string_t to_basic_string(any_t&& arg)
{
#ifdef MEOJSON_KEEP_FLOATING_PRECISION
using real_type = std::remove_reference_t<any_t>;
if constexpr (std::is_floating_point_v<real_type>) {
if constexpr (std::is_same_v<string_t, std::string>) {
std::ostringstream oss;
oss << std::setprecision(std::numeric_limits<real_type>::max_digits10) << arg;
return oss.str();
}
else if constexpr (std::is_same_v<string_t, std::wstring>) {
std::wostringstream oss;
oss << std::setprecision(std::numeric_limits<real_type>::max_digits10) << arg;
return oss.str();
}
}
#endif
if constexpr (std::is_same_v<string_t, std::string>) {
return std::to_string(std::forward<any_t>(arg));
}
Expand Down
4 changes: 4 additions & 0 deletions test/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

#include "include_test.h"
#include "json5_test.h"
#include "precision_test.h"
#include "serializing_test.h"

int main()
Expand All @@ -23,6 +24,9 @@ int main()
std::cout << "\n*** json5_test ***\n" << std::endl;
success &= test_json5();

std::cout << "\n*** precision_test ***\n" << std::endl;
success &= precision_test();

if (!success) {
std::cout << "\n****** Test failed ******\n" << std::endl;
return -1;
Expand Down
18 changes: 18 additions & 0 deletions test/precision_test.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
#define MEOJSON_KEEP_FLOATING_PRECISION

#include "../include/json.hpp"

#include <iomanip>
#include <iostream>

bool precision_test()
{
double value = 3.141592653589793;
json::object obj_old = json::object { { "double", value } };
std::string obj_str = obj_old.to_string();
std::cout << obj_str << std::endl;
json::object obj_new = json::parse(obj_str).value().as_object();
std::cout << "old:" << std::hexfloat << value << std::endl;
std::cout << "new:" << std::hexfloat << obj_new.at("double").as_double() << std::endl;
return obj_new.at("double").as_double() == value;
}
3 changes: 3 additions & 0 deletions test/precision_test.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
#pragma once

extern bool precision_test();

0 comments on commit 4607356

Please sign in to comment.