I'm having some trouble converting a number into a char. I'm using sprintf (as shown below). It works great if I try to get only 4 figures. However, if I try to get 5 figures I get a totally wrong number. I'm sure it is a easy fix, but I can't figure out what I'm doing wrong...
Using the code below, if in the 1st line I multiply using:
10000 --> newlona is 8396; newlon1 is 8396; (in this case, all is good)
100000 --> newlona is 83967; newlon1 is 18431 (here there is something "fishy" going on)
Any thoughts on what could be happening, and how I can make newlon1 show a value of "83967"?
Thanks
long newlona = (newlon - (int)newlon) * 100000; //change to increase number of figures
Serial.print(" my minsec is: ");
Serial.print(newlona);
Serial.print(" WithSprintf: ");
sprintf(newlon1,"%d", (long)newlona);
Serial.print(newlon1);
So you have a problem with newlon1 but the code that you showed doesn't tell us how newlon1 is declared or how it is computed. It smells like an int was used where a long should be used, but how can we tell?
Rule 1: Show us ALL of the code.
Rule 2: Go see Rule 1.
I will note that 83967-18431=65536 which indicates a rollover at 2 to the power of 16. This is why I suspect that a variable is declared incorrectly or a calculation has been done incorrectly.
Thanks guys so much for the responses. You guys were actually right... the number I was trying to print was a long, but it wasn't printing because as Paul wisely noted, I used the incorrect formatting directive in "sprintf". I was using %d, when instead I should have used %ld (as he pointed out).
Ufff... I just wished that I could have learned about this earlier. I kept reading & re-reading the sprintf manual (http://www.cplusplus.com/reference/cstdio/sprintf/) and never saw a mention of the %ld trick...
The format specifiers are actually defined on the printf page. It's assumed, I guess, that you know that sprintf is for doing printf to streams.
There is says:
A format specifier follows this prototype: [see compatibility note below]
%[flags][width][.precision][length]specifier
You actually have to parse this starting at the right. The specifier defines what kind of variable will be handled (integer, float, character, string, etc.).
Then, the length part may be needed. It isn't for int or float, but it is for long, long long, short, etc.
(Just so you know how to read the page, for future amusement.)