Shop OBEX P1 Docs P2 Docs Learn Events
Simple int to String with format — Parallax Forums

Simple int to String with format

PlaneTeeRPlaneTeeR Posts: 100
edited 2006-06-30 17:28 in General Discussion
I want to show 2 numbers on a LCD. But I use int as a variable.
How can i simply, with use of the format class, convert this int to string?
I don't understand the use of the format class very good.

Thanks

PlaneTeeR

Comments

  • Peter VerkaikPeter Verkaik Posts: 3,956
    edited 2006-06-30 15:43
    The Format class allows you to make asciiz strings.

    char[noparse]/noparse myString = new char[noparse][[/noparse]7]; //allow for 6 characters + closing null
    int value = -12;
    Format.sprintf(myString,"%d",value); //generates asciiz string '-','1','2',0

    You can also add some text if you prefer:
    Format.sprintf(myString,"value = %d",value);
    but then myString must be able to hold 15 characters.

    To print an asciiz string to a serial lcd use

    void printLcd(char[noparse]/noparse s) {
    · int i=0;
    · while (s[noparse][[/noparse]i]!=0) lcd.sendByte(s[noparse][[/noparse]i++]);
    }

    regards peter
  • PlaneTeeRPlaneTeeR Posts: 100
    edited 2006-06-30 16:02
    I used this:

    int value = 18;
    char[noparse]/noparse myString = new char[noparse][[/noparse]3];

    myLcd.write(Format.sprintf(myString,"%d",value));

    And on my LCD it gives a strange symbol, but not 18.

    Thanks
  • Peter VerkaikPeter Verkaik Posts: 3,956
    edited 2006-06-30 16:24
    sprintf() returns the number of bytes (excluding the closing 0) in myString.
    So use this:

    int value = 18;
    char[noparse]/noparse myString = new char[noparse][[/noparse]3];
    Format.sprintf(myString,"%d",value); //make string "18",0
    int i=0;
    while (myString[noparse][[/noparse]i]!=0) myLcd.writeByte(myString[noparse][[/noparse]i++]);

    regards peter
  • PlaneTeeRPlaneTeeR Posts: 100
    edited 2006-06-30 17:28
    This works fine, thanks
Sign In or Register to comment.