From c8c785cf0735c235b94397f38ab08f0c67f59733 Mon Sep 17 00:00:00 2001 From: vng Date: Fri, 21 Mar 2014 12:42:37 +0300 Subject: [PATCH] Fixed bug in Double -> String conversion with fixed digits after comma. --- base/base_tests/string_utils_test.cpp | 3 +++ base/string_utils.cpp | 15 ++++++++++++--- 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/base/base_tests/string_utils_test.cpp b/base/base_tests/string_utils_test.cpp index f7ed588abf..edb66c7986 100644 --- a/base/base_tests/string_utils_test.cpp +++ b/base/base_tests/string_utils_test.cpp @@ -239,6 +239,9 @@ UNIT_TEST(to_string) TEST_EQUAL(strings::to_string_dac(-10.66666666, 7), "-10.6666667", ()); TEST_EQUAL(strings::to_string_dac(10001.66666666, 8), "10001.66666666", ()); TEST_EQUAL(strings::to_string_dac(99999.99999999, 8), "99999.99999999", ()); + TEST_EQUAL(strings::to_string_dac(0.7777, 3), "0.778", ()); + TEST_EQUAL(strings::to_string_dac(-0.333333, 4), "-0.3333", ()); + TEST_EQUAL(strings::to_string_dac(2.33, 2), "2.33", ()); TEST_EQUAL(strings::to_string(-1.0E2), "-100", ()); TEST_EQUAL(strings::to_string(1.0E-2), "0.01", ()); diff --git a/base/string_utils.cpp b/base/string_utils.cpp index 091dbc6f24..673a91f8ac 100644 --- a/base/string_utils.cpp +++ b/base/string_utils.cpp @@ -4,8 +4,7 @@ #include "../std/target_os.hpp" #include "../std/iterator.hpp" #include "../std/cmath.hpp" - -#include // setprecision +#include "../std/iomanip.hpp" #include // boost::trim @@ -165,8 +164,18 @@ bool StartsWith(string const & s1, char const * s2) string to_string_dac(double d, int dac) { + double fD = fabs(d); + + // Calc digits before comma (log10). + int dbc = 0; + while (fD >= 1.0 && dbc < numeric_limits::digits10) + { + fD /= 10.0; + ++dbc; + } + ostringstream ss; - ss << std::setprecision(dac + int(log10(fabs(d))) + 1) << d; + ss << setprecision(dac + dbc) << d; return ss.str(); }