 # Representing an integer with 3 digits.

Hello, I was wondering if someone can help me with this: I need to represent an integer with 3 digits and I need my code to do this if the number as only two digits. For example: If my number is 435 then the representation will be 435. If my number is 95 then it will be printed 095. If my number is 4 then the code prints 004. Can anyone help me doing that? I am giving my first steps in Arduino. Best regards from Portugal. Duarte :)

Hello and welcome

Easy solution

``````char buf;
sprintf( buf, "%03d", num );
Serial.println( buf );
``````

And a more memory efficient solution:

``````char buf;
uint8_t i = 0;
if ( num < 100 ) buf[ i++ ] = '0';
if ( num <  10 ) buf[ i++ ] = '0';
itoa( num, buf + i, 10 );
Serial.println( buf );
``````

Both solutions assume that num is always positive and never greater than 999

In C, integer division always rounds down. So:

``````char hundreds_digit = ((x/100)%10);
char tens_digit = ((x/10)%10);
char units_digit = ((x)%10);
``````

A pedestrian but very easy to understand method

``````if (number < 10)
{
Serial.print("00");
}
else if (number < 100)
{
Serial.print("0");
}
Serial.println(number);
``````

No intermediate buffers or memory overhead from the use of sprintf()

Thank you very muchfor your help!

Best.