diff --git a/base/base_tests/string_utils_test.cpp b/base/base_tests/string_utils_test.cpp index 6bc2eed622..1a3fac8c45 100644 --- a/base/base_tests/string_utils_test.cpp +++ b/base/base_tests/string_utils_test.cpp @@ -254,9 +254,20 @@ UNIT_TEST(to_string_dac) TEST_EQUAL(strings::to_string_dac(-0.0039, 2), "-0", ()); TEST_EQUAL(strings::to_string_dac(0.0039, 2), "0", ()); + TEST_EQUAL(strings::to_string_dac(-1.0039, 2), "-1", ()); + TEST_EQUAL(strings::to_string_dac(1.0039, 2), "1", ()); TEST_EQUAL(strings::to_string_dac(0., 5), "0", ()); TEST_EQUAL(strings::to_string_dac(0., 0), "0", ()); + + TEST_EQUAL(strings::to_string_dac(1.0, 6), "1", ()); + TEST_EQUAL(strings::to_string_dac(0.9, 6), "0.9", ()); + TEST_EQUAL(strings::to_string_dac(-1.0, 30), "-1", ()); + TEST_EQUAL(strings::to_string_dac(-0.99, 30), "-0.99", ()); + + TEST_EQUAL(strings::to_string_dac(1.0E30, 6), "1e+30", ()); + TEST_EQUAL(strings::to_string_dac(1.0E-15, 15), "0.000000000000001", ()); + TEST_EQUAL(strings::to_string_dac(1.0 + 1.0E-14, 15), "1.00000000000001", ()); } struct FunctorTester diff --git a/base/string_utils.cpp b/base/string_utils.cpp index 6a5c42bb9a..2de39807af 100644 --- a/base/string_utils.cpp +++ b/base/string_utils.cpp @@ -118,9 +118,12 @@ namespace { char ascii_to_lower(char in) { - static char const diff = 'Z'-'z'; - if (in <= 'Z' && in >= 'A') - return (in-diff); + char const diff = 'z' - 'Z'; + STATIC_ASSERT(diff == 'a' - 'A'); + STATIC_ASSERT(diff > 0); + + if (in >= 'A' && in <= 'Z') + return (in + diff); return in; } } @@ -169,7 +172,10 @@ bool StartsWith(string const & s1, char const * s2) string to_string_dac(double d, int dac) { + dac = min(numeric_limits::digits10, dac); + ostringstream ss; + if (d < 1. && d > -1.) { string res; @@ -188,17 +194,15 @@ string to_string_dac(double d, int dac) return res; } - double fD = fabs(d); - // Calc digits before comma (log10). - int dbc = 0; - while (fD >= 1.0 && dbc < numeric_limits::digits10) + double fD = fabs(d); + while (fD >= 1.0 && dac < numeric_limits::digits10) { fD /= 10.0; - ++dbc; + ++dac; } - ss << setprecision(dac + dbc) << d; + ss << setprecision(dac) << d; return ss.str(); }