diff --git a/mysql-test/r/func_math.result b/mysql-test/r/func_math.result
index 307f17141329d9b4786d966a4a5b43cc0f47e06d..bfb3af0afffe15c4b9c91d6f7d9c84ec789f00a4 100644
--- a/mysql-test/r/func_math.result
+++ b/mysql-test/r/func_math.result
@@ -600,3 +600,10 @@ NULL
 SELECT -9223372036854775808 MOD -1;
 -9223372036854775808 MOD -1
 0
+#
+# Bug #57209 valgrind + Assertion failed: dst > buf 
+#
+SELECT floor(log10(format(concat_ws(5445796E25, 5306463, 30837), -358821)))
+as foo;
+foo
+2
diff --git a/mysql-test/t/func_math.test b/mysql-test/t/func_math.test
index 44af2f5ad3f575542d24be7dbc1f1d6a7bb2af49..efdf7201a40ae17e5457d50ac4e674f86cf9287a 100644
--- a/mysql-test/t/func_math.test
+++ b/mysql-test/t/func_math.test
@@ -458,3 +458,9 @@ SELECT 2 DIV -2;
 SELECT -(1 DIV 0);
 # Crashed the server with SIGFPE before the bugfix
 SELECT -9223372036854775808 MOD -1;
+
+--echo #
+--echo # Bug #57209 valgrind + Assertion failed: dst > buf 
+--echo #
+SELECT floor(log10(format(concat_ws(5445796E25, 5306463, 30837), -358821)))
+as foo;
diff --git a/sql/item_strfunc.cc b/sql/item_strfunc.cc
index 6d3514bf356e1f1107a71e79c526eeb3b1940972..89c1e785c719c74ee5203c85ac7b70f688f0bc05 100644
--- a/sql/item_strfunc.cc
+++ b/sql/item_strfunc.cc
@@ -2299,7 +2299,8 @@ String *Item_func_format::val_str_ascii(String *str)
   if (lc->grouping[0] > 0 &&
       str_length >= dec_length + 1 + lc->grouping[0])
   {
-    char buf[DECIMAL_MAX_STR_LENGTH * 2]; /* 2 - in the worst case when grouping=1 */
+    /* We need space for ',' between each group of digits as well. */
+    char buf[2 * FLOATING_POINT_BUFFER];
     int count;
     const char *grouping= lc->grouping;
     char sign_length= *str->ptr() == '-' ? 1 : 0;
@@ -2323,7 +2324,7 @@ String *Item_func_format::val_str_ascii(String *str)
         count will be initialized to -1 and
         we'll never get into this "if" anymore.
       */
-      if (!count)
+      if (count == 0)
       {
         *--dst= lc->thousand_sep;
         if (grouping[1])