From 877096d49d0a6498e89142f1b515973b4af383f7 Mon Sep 17 00:00:00 2001 From: Benoit Blanchon Date: Thu, 23 Apr 2015 21:27:58 +0200 Subject: [PATCH] Fixed issue #67 --- src/Arduino/Print.cpp | 21 +++++++++++++++++-- test/Issue67.cpp | 47 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 66 insertions(+), 2 deletions(-) create mode 100644 test/Issue67.cpp diff --git a/src/Arduino/Print.cpp b/src/Arduino/Print.cpp index 0812228d..dbcd9a0a 100644 --- a/src/Arduino/Print.cpp +++ b/src/Arduino/Print.cpp @@ -8,7 +8,8 @@ #include "../../include/ArduinoJson/Arduino/Print.hpp" -#include // for sprintf +#include // for isnan() and isinf() +#include // for sprintf() size_t Print::print(const char s[]) { size_t n = 0; @@ -19,8 +20,24 @@ size_t Print::print(const char s[]) { } size_t Print::print(double value, int digits) { + // https://github.com/arduino/Arduino/blob/db8cbf24c99dc930b9ccff1a43d018c81f178535/hardware/arduino/sam/cores/arduino/Print.cpp#L218 + if (isnan(value)) return print("nan"); + if (isinf(value)) return print("inf"); + char tmp[32]; - sprintf(tmp, "%.*f", digits, value); + + // https://github.com/arduino/Arduino/blob/db8cbf24c99dc930b9ccff1a43d018c81f178535/hardware/arduino/sam/cores/arduino/Print.cpp#L220 + bool isBigDouble = value > 4294967040.0 || value < -4294967040.0; + + if (isBigDouble) { + // Arduino's implementation prints "ovf" + // We prefer trying to use scientific notation, since we have sprintf + sprintf(tmp, "%g", value); + } else { + // Here we have the exact same output as Arduino's implementation + sprintf(tmp, "%.*f", digits, value); + } + return print(tmp); } diff --git a/test/Issue67.cpp b/test/Issue67.cpp new file mode 100644 index 00000000..c665e140 --- /dev/null +++ b/test/Issue67.cpp @@ -0,0 +1,47 @@ +// Copyright Benoit Blanchon 2014-2015 +// MIT License +// +// Arduino JSON library +// https://github.com/bblanchon/ArduinoJson + +#include +#include + +class Issue67 : public testing::Test { + public: + void whenInputIs(double value) { _variant = value; } + + void outputMustBe(const char* expected) { + char buffer[1024]; + _variant.printTo(buffer, sizeof(buffer)); + ASSERT_STREQ(expected, buffer); + } + + private: + JsonVariant _variant; +}; + +TEST_F(Issue67, BigPositiveDouble) { + whenInputIs(1e100); + outputMustBe("1e+100"); +} + +TEST_F(Issue67, BigNegativeDouble) { + whenInputIs(-1e100); + outputMustBe("-1e+100"); +} + +TEST_F(Issue67, Zero) { + whenInputIs(0.0); + outputMustBe("0.00"); +} + +TEST_F(Issue67, SmallPositiveDouble) { + whenInputIs(111.111); + outputMustBe("111.11"); +} + +TEST_F(Issue67, SmallNegativeDouble) { + whenInputIs(-111.111); + outputMustBe("-111.11"); +}