While working on a project with the Arduino, I was frustrated by the lack of double-to-string functionality. I scoured the web and only found “dumb implementations” that only worked to a fixed precision and did not support larger ranges (outside the (long/int) boundaries).

So I’ve written one myself. I haven’t had any problems with it, but if anyone notices any bugs it’d be greatly appreciated. Hopefully this will help others in the future , would’ve saved me quite some time. And also hope I put this in the right section . Let me know what you guys think!

This will use “E+” or “E-” when the numbers start going out of range, and will shift accordingly to get the best precision (it’s not “125333.00” and “0.32” and “235.30”, it’s just “12533” and “0.32” and “235.3”).

```
#include <Arduino.h>
#include <math.h>
#define INTEGER_MAX (pow(2,31)-1)
#define E_MAX (pow(10, 7))
#define E_MIN (pow(10, -6))
#define EPSILON 0.000000119209
int compareNums(double x, double y) {
if (abs(x - y) <= EPSILON) {
return 0;
} else if (x > y) {
return 1;
} else {
return -1;
}
}
String doubleToString(double d) {
String bin = "";
if (!isfinite(d)) {
return "NaN";
}
if (d < 0) {
d *= -1;
bin += "-";
}
if (compareNums(d, E_MAX) >= 0) { //use E+
int e = 0;
while (compareNums(d, 10) >= 0) { //while d is greater than or equal to 10 (not in scientific form)
d /= 10;
e++;
}
while (compareNums(d, (long) d) != 0) { //while not an integer
d *= 10;
}
String str = String((long) d);
bin += str.substring(0, 1) + "." + str.substring(1) + "E+" + String(e);
} else if (compareNums(d, 1) == -1) { //between 0-1
if (compareNums(d, E_MIN) == -1) { //use E-
int e = 0;
while (d < 1) { //while d is not in scientific form
d *= 10;
e++;
}
while (compareNums(d, (long) d) != 0) { //while not an integer
d *= 10;
}
String str = String((long) d);
bin += str.substring(0, 1) + "." + str.substring(1) + "E-" + String(e);
} else { //regular decimal less than 0
int decimals = 0;
while (compareNums(d, (long) d) != 0) { //while not an integer
d *= 10;
decimals++;
}
String str = String((long) d);
bin += "0.";
for (int i = 0; i < decimals - 1; i++) {
bin += "0";
}
bin += str;
}
} else { //regular decimal
int decimals = 0;
while (compareNums(d, (long) d) != 0) { //while not an integer
d *= 10;
decimals++;
}
String str = String((long) d);
if (decimals == 0) {
bin += str;
} else {
bin += str.substring(0, str.length() - decimals) + "." + str.substring(str.length() - decimals);
}
}
return bin;
}
```