Merge pull request #8742 from Icinga/bugfix/double-to-string

Convert::ToString(double): handle integral values too large for long long correctly
This commit is contained in:
Julian Brost 2021-06-15 12:28:15 +02:00 committed by GitHub
commit 005fac0a23
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 6 additions and 3 deletions

View File

@ -3,6 +3,7 @@
#include "base/convert.hpp"
#include "base/datetime.hpp"
#include <boost/lexical_cast.hpp>
#include <iomanip>
using namespace icinga;
@ -21,10 +22,10 @@ String Convert::ToString(double val)
double integral;
double fractional = std::modf(val, &integral);
if (fractional == 0)
return Convert::ToString(static_cast<long long>(val));
std::ostringstream msgbuf;
if (fractional == 0) {
msgbuf << std::setprecision(0);
}
msgbuf << std::fixed << val;
return msgbuf.str();
}

View File

@ -33,12 +33,14 @@ BOOST_AUTO_TEST_CASE(tostring)
BOOST_CHECK(Convert::ToString(7) == "7");
BOOST_CHECK(Convert::ToString(7.5) == "7.500000");
BOOST_CHECK(Convert::ToString("hello") == "hello");
BOOST_CHECK(Convert::ToString(18446744073709551616.0) == "18446744073709551616"); // pow(2, 64)
String str = "hello";
BOOST_CHECK(Convert::ToString(str) == "hello");
BOOST_CHECK(Convert::ToString(Value(7)) == "7");
BOOST_CHECK(Convert::ToString(Value(7.5)) == "7.500000");
BOOST_CHECK(Convert::ToString(Value(18446744073709551616.0)) == "18446744073709551616"); // pow(2, 64)
BOOST_CHECK(Convert::ToString(Value("hello")) == "hello");
BOOST_CHECK(Convert::ToString(Value("hello hello")) == "hello hello");
}