MCPcopy Create free account
hub / github.com/andysworkshop/stm32plus / modp_dtoa

Function modp_dtoa

lib/src/string/StringUtil.cpp:144–268  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

142 */
143
144 uint16_t modp_dtoa(double value,int8_t prec,char *str) {
145
146 static const double pow10[] = { 1,10,100,1000,10000,100000,1000000,10000000,100000000,1000000000 };
147 uint16_t length;
148
149 if(!(value==value)) {
150
151 str[0]='n';
152 str[1]='a';
153 str[2]='n';
154 str[3]='\0';
155 return 3;
156 }
157
158 int8_t count;
159 double diff=0.0;
160 char *wstr=str;
161
162 // we'll work in positive values and deal with the negative sign issue later
163
164 bool neg=false;
165
166 if(value<0) {
167 neg=true;
168 value=-value;
169 }
170
171 uint32_t whole=(uint32_t)value;
172 double tmp=(value-whole)*pow10[prec];
173 uint32_t frac=(uint32_t)(tmp);
174
175 diff=tmp-frac;
176
177 if(diff>0.5) {
178
179 ++frac;
180
181 // handle rollover, e.g. case 0.99 with prec 1 is 1.0
182
183 if(frac>=pow10[prec]) {
184 frac=0;
185 ++whole;
186 }
187
188 } else if(diff==0.5 && ((frac==0) || (frac & 1))) {
189
190 // if halfway, round up if odd, OR if last digit is 0. That last part is strange
191
192 ++frac;
193 }
194
195 if(prec==0) {
196
197 diff=value-whole;
198
199 if(diff>0.5) {
200 // greater than 0.5, round up, e.g. 1.6 -> 2
201

Callers 4

GraphicTerminal.hFile · 0.85
SemiHostingClass · 0.85
TextOutputStream.hFile · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected