@@ -133,16 +133,24 @@ String::String(unsigned long long value, unsigned char base)
133
133
134
134
String::String (float value, unsigned char decimalPlaces)
135
135
{
136
+ int len = digitsBe4Decimal (value);
136
137
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);
139
143
}
140
144
141
145
String::String (double value, unsigned char decimalPlaces)
142
146
{
147
+ int len = digitsBe4Decimal (value);
143
148
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);
146
154
}
147
155
148
156
String::~String ()
@@ -362,15 +370,17 @@ unsigned char String::concat(unsigned long long num)
362
370
363
371
unsigned char String::concat (float num)
364
372
{
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);
367
376
return concat (string, strlen (string));
368
377
}
369
378
370
379
unsigned char String::concat (double num)
371
380
{
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);
374
384
return concat (string, strlen (string));
375
385
}
376
386
@@ -797,3 +807,27 @@ float String::toFloat(void) const
797
807
if (buffer) return float (atof (buffer));
798
808
return 0 ;
799
809
}
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