Skip to content

Commit c8c6e43

Browse files
committed
dtostrf: use width argument
Fix stm32duino#44 Handle minimum field width of the output string width is signed value, negative for left adjustment. Range -128,127 Signed-off-by: Frederic.Pillon <[email protected]>
1 parent 44f6cf2 commit c8c6e43

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

cores/arduino/avr/dtostrf.c

+28
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,8 @@
1919
*/
2020

2121
#include <stdio.h>
22+
#include <stdlib.h>
23+
#include <string.h>
2224

2325
char *dtostrf (double val, signed char width, unsigned char prec, char *sout) {
2426
//Commented code is the original version
@@ -59,5 +61,31 @@ char *dtostrf (double val, signed char width, unsigned char prec, char *sout) {
5961

6062
sprintf(sout, "%ld.%ld", int_part, dec_part);
6163

64+
// Handle minimum field width of the output string
65+
// width is signed value, negative for left adjustment.
66+
// Range -128,127
67+
char fmt[129] = "";
68+
unsigned int w = width;
69+
if (width < 0) {
70+
negative = 1;
71+
w = -width;
72+
} else {
73+
negative = 0;
74+
}
75+
76+
if(strlen(sout) < w) {
77+
memset(fmt, ' ', 128);
78+
fmt[w-strlen(sout)] = '\0';
79+
if(negative == 0) {
80+
char *tmp = strdup(sout);
81+
strcpy(sout,fmt);
82+
strcat(sout, tmp);
83+
free(tmp);
84+
} else {
85+
// left adjustment
86+
strcat(sout, fmt);
87+
}
88+
}
89+
6290
return sout;
6391
}

0 commit comments

Comments
 (0)