writeFloat.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. // Copyright Benoit Blanchon 2014-2017
  2. // MIT License
  3. //
  4. // Arduino JSON library
  5. // https://bblanchon.github.io/ArduinoJson/
  6. // If you like this project, please add a star!
  7. #include <catch.hpp>
  8. #include <limits>
  9. #include <string>
  10. #include <ArduinoJson/Serialization/DynamicStringBuilder.hpp>
  11. #include <ArduinoJson/Serialization/JsonWriter.hpp>
  12. using namespace ArduinoJson::Internals;
  13. void check(double input, const std::string& expected) {
  14. std::string output;
  15. DynamicStringBuilder<std::string> sb(output);
  16. JsonWriter<DynamicStringBuilder<std::string> > writer(sb);
  17. writer.writeFloat(input);
  18. REQUIRE(writer.bytesWritten() == output.size());
  19. CHECK(expected == output);
  20. }
  21. TEST_CASE("JsonWriter::writeFloat()") {
  22. SECTION("Pi") {
  23. check(3.14159265359, "3.141592654");
  24. }
  25. SECTION("Signaling NaN") {
  26. double nan = std::numeric_limits<double>::signaling_NaN();
  27. check(nan, "NaN");
  28. }
  29. SECTION("Quiet NaN") {
  30. double nan = std::numeric_limits<double>::quiet_NaN();
  31. check(nan, "NaN");
  32. }
  33. SECTION("Infinity") {
  34. double inf = std::numeric_limits<double>::infinity();
  35. check(inf, "Infinity");
  36. check(-inf, "-Infinity");
  37. }
  38. SECTION("Zero") {
  39. check(0.0, "0");
  40. check(-0.0, "0");
  41. }
  42. SECTION("Espilon") {
  43. check(2.2250738585072014E-308, "2.225073859e-308");
  44. check(-2.2250738585072014E-308, "-2.225073859e-308");
  45. }
  46. SECTION("Max double") {
  47. check(1.7976931348623157E+308, "1.797693135e308");
  48. check(-1.7976931348623157E+308, "-1.797693135e308");
  49. }
  50. SECTION("Big exponent") {
  51. // this test increases coverage of normalize()
  52. check(1e255, "1e255");
  53. check(1e-255, "1e-255");
  54. }
  55. SECTION("Exponentation when <= 1e-5") {
  56. check(1e-4, "0.0001");
  57. check(1e-5, "1e-5");
  58. check(-1e-4, "-0.0001");
  59. check(-1e-5, "-1e-5");
  60. }
  61. SECTION("Exponentation when >= 1e7") {
  62. check(9999999.999, "9999999.999");
  63. check(10000000, "1e7");
  64. check(-9999999.999, "-9999999.999");
  65. check(-10000000, "-1e7");
  66. }
  67. SECTION("Rounding when too many decimals") {
  68. check(0.000099999999999, "0.0001");
  69. check(0.0000099999999999, "1e-5");
  70. }
  71. SECTION("9 decimal places") {
  72. check(0.100000001, "0.100000001");
  73. check(0.999999999, "0.999999999");
  74. check(9.000000001, "9.000000001");
  75. check(9.999999999, "9.999999999");
  76. }
  77. SECTION("10 decimal places") {
  78. check(0.1000000001, "0.1");
  79. check(0.9999999999, "1");
  80. check(9.0000000001, "9");
  81. check(9.9999999999, "10");
  82. }
  83. }