The most effective way to format numbers on Arduino I made a big search about how to Format Numbers with the Arduino. I want to format unsigned Longs into a String in this format: "23,854,972".

The most of the snippets I found work only with the standard C / C++ Libraries. They dont work on the Arduino until I should put some STL libraries on the Arduino, which I want to prevent. It would be too bit of a overhead to import these only for this task. Also these Libraries will of course use some additional Flash and SRAM.

For my Application it is very important that the solution uses the minimum Flash, SRAM and is fast.

Even if a solution does not use STL or works only with the native Arduino Libraries, I would need help to decide which one is more effective in the sense of speed.

Incoming Number: 23854972
Arduino Program Output: 23,854,972
Here is my try at it: The usual way to write a number in decimal is to
get the digits from right to left with a loop that looks something like



digit = '0' + val % 10;
val /= 10;


The following function does exactly this, with the addition of adding
commas at the correct positions:

/*
 * Format an unsigned long (32 bits) into a string in the format
 * "23,854,972".
 *
 * The provided buffer must be at least 14 bytes long. The number will
 * be right-adjusted in the buffer. Returns a pointer to the first
 * digit.
 */
char *ultoa(unsigned long val, char *s)
{
    char *p = s + 13;
    *p = '\0';
    do {
        if ((p - s) % 4 == 2)
            *--p = ',';
        *--p = '0' + val % 10;
        val /= 10;
    } while (val);
    return p;
}


Note that the string is right adjusted in the buffer, and the unused
characters are not touched. This means you can get a right adjusted
string by:


pre-filling the string with spaces (for padding)
calling the function above
using the original buffer as the right adjusted string


Otherwise you would use the returned pointer to have a string with no
padding.

Here is a simple test program:

unsigned long vals[] = {0, 1, 2, 9, 10, 999, 1000, 0xffffffff};
const int COUNT = sizeof vals / sizeof vals[0];

void setup()
{
    Serial.begin(9600);
    char buffer[14];
    for (int i = 0; i &lt; COUNT; i++) {
        unsigned long val = vals[i];
        Serial.print(val);
        Serial.write('\t');
        Serial.println(ultoa(val, buffer));
    }
}

void loop() {}