From 1885f4bc5f7a223ebdbd83cbf1177e01cc984353 Mon Sep 17 00:00:00 2001 From: Kirill Lokotkov Date: Wed, 25 Jan 2023 18:33:40 +0300 Subject: [PATCH] Fix for printing long doubles bug in dump_float When you use long double as a floating point type with the current version of this file and try to dump json it prints trash instead of actual number. This if-else fixes the problem. On using long double you just need to add an 'L' modifier before 'g' in format string. --- include/nlohmann/detail/output/serializer.hpp | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/include/nlohmann/detail/output/serializer.hpp b/include/nlohmann/detail/output/serializer.hpp index 02bfaa548..c3e8d291d 100644 --- a/include/nlohmann/detail/output/serializer.hpp +++ b/include/nlohmann/detail/output/serializer.hpp @@ -832,7 +832,12 @@ class serializer // the actual conversion // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg,hicpp-vararg) - std::ptrdiff_t len = (std::snprintf)(number_buffer.data(), number_buffer.size(), "%.*g", d, x); + std::ptrdiff_t len; + if constexpr (std::is_same_v) { + len = (std::snprintf)(number_buffer.data(), number_buffer.size(), "%.*Lg", d, x); + } else { + len = (std::snprintf)(number_buffer.data(), number_buffer.size(), "%.*g", d, x); + } // negative value indicates an error JSON_ASSERT(len > 0);