Formatted printing of a "pseudo" float is not that easy as I thought. To avoid floats I use int (or long) with a unit of tenth or hundredth. To print them, I have to add a comma, fill up with zeros and correct the minus sign.
My solution is the following code using sprintf(), but i think this code is not good and effective. The code needs not to be fast, a Serial.print (or lcd.print) of this number anyway needs 1-3ms.
Suggestions of optimization and simplification are welcome. ![]()
I have also tried without sprintf(), and adding up each decimal place to single char's, but the code will get much more complex (and I've given up).
(Range checks are missing in the code)
// usage: Serial.println(intToString(buffer, -1234, 6, 2)); -> " -12.34"
char * intToString(char * outstr, int value, byte totalLen, byte decMove) {
if (decMove==0) {
char formatS[10] = {'%',totalLen+48,'d','\0'};
sprintf(outstr, formatS,value);
} else {
int factor = 1;
for (int i=0; i<decMove; i++) { factor *=10; }
char formatS[10] = {'%',totalLen-decMove+47,'d','.','%','0',decMove+48,'d','\0'};
// Format-String like "%4d.%02d"
sprintf(outstr, formatS,value/factor,abs(value%factor));
// missing '-' at eg. -5 > "0.05"
if ((value < 0) && (value > -factor)) { outstr[totalLen-decMove-3]='-'; }
}
return outstr;
}
void TestIntToString() {
char buffer[10];
Serial.println(intToString(buffer, 12, 5, 2));
Serial.println(intToString(buffer, -1, 5, 2));
Serial.println(intToString(buffer, -1234, 5, 2));
}
Thank's for any suggestions, Norbert