@@ -133,16 +133,24 @@ String::String(unsigned long long value, unsigned char base)
133133
134134String::String (float value, unsigned char decimalPlaces)
135135{
136+ int len = digitsBe4Decimal (value);
136137 init ();
137- char buf[33 ];
138- *this = dtostrf (value, (33 - 1 ), decimalPlaces, buf);
138+
139+ if (decimalPlaces) len = 1 + ((int )decimalPlaces & 0x0FF );
140+
141+ char buf[len+1 ];
142+ *this = dtostrf (value, 0 , decimalPlaces, buf);
139143}
140144
141145String::String (double value, unsigned char decimalPlaces)
142146{
147+ int len = digitsBe4Decimal (value);
143148 init ();
144- char buf[33 ];
145- *this = dtostrf (value, (33 - 1 ), decimalPlaces, buf);
149+
150+ if (decimalPlaces) len = 1 + ((int )decimalPlaces & 0x0FF );
151+
152+ char buf[len+1 ];
153+ *this = dtostrf (value, 0 , decimalPlaces, buf);
146154}
147155
148156String::~String ()
@@ -362,15 +370,17 @@ unsigned char String::concat(unsigned long long num)
362370
363371unsigned char String::concat (float num)
364372{
365- char buf[20 ];
366- char * string = dtostrf (num, (20 - 1 ), 2 , buf);
373+ int len = digitsBe4Decimal (num);
374+ char buf[len+1 +2 +1 ]; // The integer portion, 1 decimal point, 2 precision and 1 null char
375+ char * string = dtostrf (num, 0 , 2 , buf);
367376 return concat (string, strlen (string));
368377}
369378
370379unsigned char String::concat (double num)
371380{
372- char buf[20 ];
373- char * string = dtostrf (num, (20 - 1 ), 2 , buf);
381+ int len = digitsBe4Decimal (num);
382+ char buf[len+1 +2 +1 ]; // The integer portion, 1 decimal point, 2 precision and 1 null char
383+ char * string = dtostrf (num, 0 , 2 , buf);
374384 return concat (string, strlen (string));
375385}
376386
@@ -797,3 +807,27 @@ float String::toFloat(void) const
797807 if (buffer) return float (atof (buffer));
798808 return 0 ;
799809}
810+
811+ /* ********************************************/
812+ /* utilities functions */
813+ /* ********************************************/
814+
815+ int String::digitsBe4Decimal (double number)
816+ {
817+ int cnt = 0 ;
818+ long tmp = (long )number; // Drop the decimal here
819+
820+ // Count -ve sign as one digit
821+ if (tmp < 0 ) {
822+ cnt++;
823+ tmp = -tmp;
824+ }
825+
826+ // Count the number of digit
827+ while (tmp) {
828+ tmp /= 10 ;
829+ cnt++;
830+ }
831+ return cnt;
832+ }
833+
0 commit comments