Author zitron: http://forum.arduino.cc/index.php?topic=37391#msg276209 modified by ADiea: remove dependencies strcat, floor, round; reorganize+speedup code
| 113 | // Author zitron: http://forum.arduino.cc/index.php?topic=37391#msg276209 |
| 114 | // modified by ADiea: remove dependencies strcat, floor, round; reorganize+speedup code |
| 115 | char *dtostrf_p(double floatVar, int minStringWidthIncDecimalPoint, int numDigitsAfterDecimal, char *outputBuffer, char pad) |
| 116 | { |
| 117 | char temp[40], num[40]; |
| 118 | unsigned long mult = 1, int_part; |
| 119 | int16_t i, processedFracLen = numDigitsAfterDecimal; |
| 120 | |
| 121 | if(processedFracLen < 0) |
| 122 | processedFracLen = 9; |
| 123 | |
| 124 | if (outputBuffer == nullptr) |
| 125 | return nullptr; |
| 126 | |
| 127 | if (std::isnan(floatVar)) |
| 128 | strcpy(outputBuffer, "NaN"); |
| 129 | else if (std::isinf(floatVar)) |
| 130 | strcpy(outputBuffer, "Inf"); |
| 131 | else if (floatVar > 4294967040.0) // constant determined empirically |
| 132 | strcpy(outputBuffer, "OVF"); |
| 133 | else if (floatVar < -4294967040.0) // constant determined empirically |
| 134 | strcpy(outputBuffer, "ovf"); |
| 135 | else |
| 136 | { |
| 137 | //start building the number |
| 138 | //buf will be the end pointer |
| 139 | char* buf = num; |
| 140 | |
| 141 | if (floatVar < 0.0) |
| 142 | { |
| 143 | *buf++ = '-'; //print "-" sign |
| 144 | floatVar = -floatVar; |
| 145 | } |
| 146 | |
| 147 | // Extract the integer part of the number and print it |
| 148 | |
| 149 | if (processedFracLen > 9) |
| 150 | processedFracLen = 9; // Prevent overflow! |
| 151 | |
| 152 | i = processedFracLen; |
| 153 | |
| 154 | while (i-- > 0) |
| 155 | mult *= 10; |
| 156 | |
| 157 | //round the number |
| 158 | floatVar += 0.5 / (float) mult; |
| 159 | |
| 160 | int_part = (unsigned long) floatVar; |
| 161 | |
| 162 | //print the int part into num |
| 163 | char* s = ultoa(int_part, buf, 10); |
| 164 | |
| 165 | //adjust end pointer |
| 166 | buf += strlen(s); //go to end of string |
| 167 | |
| 168 | //deal with digits after the decimal |
| 169 | if (numDigitsAfterDecimal != 0) |
| 170 | { |
| 171 | *buf++ = '.'; // print the decimal point |
| 172 |
no test coverage detected