diff --git a/docs/tostring.md b/docs/tostring.md index adce3cc7..f6dec94b 100644 --- a/docs/tostring.md +++ b/docs/tostring.md @@ -127,6 +127,17 @@ inside the `StringMaker` specialization, like so: This assertion will fail and print out the `testFloat1` and `testFloat2` to 15 decimal places. +`StringMaker` and `StringMaker` default to using fixed output, +but can be set to use scientific notation by modifying the `format` static +variable: + +```cpp + Catch::StringMaker::format = std::scientific; + const float testFloat1 = 1e-5f; + const float testFloat2 = 1e-6f; + REQUIRE(testFloat1 == testFloat2); +``` + --- [Home](Readme.md#top) diff --git a/src/catch2/catch_tostring.cpp b/src/catch2/catch_tostring.cpp index 8b0ffe01..24dded0e 100644 --- a/src/catch2/catch_tostring.cpp +++ b/src/catch2/catch_tostring.cpp @@ -42,14 +42,14 @@ namespace Detail { }; template - std::string fpToString(T value, int precision) { + std::string fpToString(T value, int precision, std::ios_base &(*format)(std::ios_base &)) { if (Catch::isnan(value)) { return "nan"; } ReusableStringStream rss; rss << std::setprecision(precision) - << std::fixed + << format << value; std::string d = rss.str(); std::size_t i = d.find_last_not_of('0'); @@ -225,15 +225,17 @@ std::string StringMaker::convert(unsigned char c) { } int StringMaker::precision = 5; +std::ios_base &(*StringMaker::format)(std::ios_base &) = std::fixed; std::string StringMaker::convert(float value) { - return Detail::fpToString(value, precision) + 'f'; + return Detail::fpToString(value, precision, format) + 'f'; } int StringMaker::precision = 10; +std::ios_base &(*StringMaker::format)(std::ios_base &) = std::fixed; std::string StringMaker::convert(double value) { - return Detail::fpToString(value, precision); + return Detail::fpToString(value, precision, format); } } // end namespace Catch @@ -241,4 +243,3 @@ std::string StringMaker::convert(double value) { #if defined(__clang__) # pragma clang diagnostic pop #endif - diff --git a/src/catch2/catch_tostring.hpp b/src/catch2/catch_tostring.hpp index d0f799a0..e53b63d3 100644 --- a/src/catch2/catch_tostring.hpp +++ b/src/catch2/catch_tostring.hpp @@ -271,12 +271,14 @@ namespace Catch { struct StringMaker { static std::string convert(float value); static int precision; + static std::ios_base &(*format)(std::ios_base &); }; template<> struct StringMaker { static std::string convert(double value); static int precision; + static std::ios_base &(*format)(std::ios_base &); }; template