Go Down

Topic: Converting number 7 to 07 (Read 428 times) previous topic - next topic

dansku

Hi all, im trying to build a lcd clock, and would like some help here.

I believe this is quite simple, i just don't know how to do it, and didn't found it how to do it with arduino.

I want to print one number, for example 7, but want it to have 2 digits, like 07.

if it was C it would be like printf("%.2d \n",x);

i'm using this

lcd.printIn(itoa(hour, buf, 10)); , want that the variable hour comes with two digits

thanks!

chippey

#1
Aug 03, 2008, 06:19 pm Last Edit: Aug 03, 2008, 06:22 pm by chippey Reason: 1
You could test the length of the resulting string, and if it's one character, print a 0 before you print the number.

This is just coding off the top of my head, so this may not work:
Code: [Select]


 int length;
 length = sizeof(itoa(hour,buf,10))/sizeof(char);
 if (length==1) lcd.printIn("0"); //assumes the number will at max only be two digits
 lcd.printIn(itoa(hour, buf, 10));



That can cleaned up some, but that's just off the top of my head.  Does that help at all?

mem

#2
Aug 03, 2008, 06:29 pm Last Edit: Aug 03, 2008, 06:30 pm by mem Reason: 1
this is the code I use in my clock sketches, change the serial.print as approprite for your lcd print routine:

Code: [Select]

void printDigits(byte digits){
 // utility function for digital clock display of minutes or seconds,  prints preceding colon and leading 0
 Serial.print(":");
 if(digits < 10)
   Serial.print('0');
 Serial.print(digits,DEC);
}

dansku

thanks mem, it worked that way =)

Go Up
 


Please enter a valid email to subscribe

Confirm your email address

We need to confirm your email address.
To complete the subscription, please click the link in the email we just sent you.

Thank you for subscribing!

Arduino
via Egeo 16
Torino, 10131
Italy