The most effective way to format numbers on Arduino
If "effective way" is minimum effort you could hack the avr-libc source code for ltoa and do something like below:
char *ultos_recursive(unsigned long val, char *s, unsigned radix, int pos)
{
int c;
if (val >= radix)
s = ultos_recursive(val / radix, s, radix, pos+1);
c = val % radix;
c += (c < 10 ? '0' : 'a' - 10);
*s++ = c;
if (pos % 3 == 0) *s++ = ',';
return s;
}
char *ltos(long val, char *s, int radix)
{
if (radix < 2 || radix > 36) {
s[0] = 0;
} else {
char *p = s;
if (radix == 10 && val < 0) {
val = -val;
*p++ = '-';
}
p = ultos_recursive(val, p, radix, 0) - 1;
*p = 0;
}
return s;
}
void setup()
{
Serial.begin(9600);
while (!Serial);
char buf[32];
Serial.println(ltos(12345678, buf, 10));
Serial.println(ltos(-12345678, buf, 10));
}
void loop()
{
}
Gives the output:
12,345,678
-12,345,678
Cheers!
PS: Please see the table driven, non-recursive, number conversion in CosaCosa (source and benchmark) for a lean and fastfaster implementation.