Printing long value with sprintf

I have been fighting with this for a long time. The code snipped below is to illustrate my problem.

I have a assigned a long value. This is a 4 byte signed value. I assign it a number that is larger then would fit in a 2 byte integer.

When I just print the value direct it is correctly displayed.
When I use formated printing with sprintf the result is wrong. It seems that sprintf %d only works on the least significant bytes of the 4 byte long value. The sprintf works ok for number below 32767 (0X7FFF).

Is this a bugg? Is this a restriction of the compiler? Do I need a special format string in stead of %d?
I want the formatted output as this is the way to get the number correctly alligned.

Does some body know how? Or do I have to program my own formatting routine?

#include <LiquidCrystal.h>

LiquidCrystal lcd(12, 11, 10, 5, 4, 3, 2);
// Pins for LCD: RS , RW , E , D4 , D5, D6 ,D7

long lvalue = 500000l;
char line[64];

void setup() {

lcd.begin(16, 2);

lcd.setCursor (0,0);
lcd.print (lvalue); // this prints correct value 500000

sprintf(line, “%6d”, lvalue) ;
lcd.setCursor (0,1);
lcd.print (line); // this pints -24288


void loop() {
// put your main code here, to run repeatedly:


What happens if you use %6dl (that’s an L) in the format string?

Is this a bugg? Is this a restriction of the compiler? Do I need a special format string in stead of %d?

No, no, and, of course.

Thanks for the quick replies.

I had to use 'ld' as in the line below.

sprintf(line, "%6ld", lvalue) ;

lvalue and rvalue have specific meaning in programming languages. They are not good variable names.

I don't have an LCD handy, but the version using sprint() compiled to 3916 bytes. The version below:

long val = 500000L;
char line[64];

void setup() {

  Serial.println(val);     // this prints correct value 500000

//  sprintf(line, "%6ld", val) ;

  ltoa(val, line, 10);
  Serial.println(line);        // this pints -24288


compiles to 2592 bytes. While sprintf() is a very powerful function, rarely does one program use a significant fraction of that power. In most cases, you can accomplish the same end result with other C functions and save a noticeable chunk of memory in the process.

Also, please read Nick Gammon's post at the top of this Forum on the proper way to post source code using code tags.