Manipulating the display of an interger

I am wondering of there is a clean way of doing this. I have a unsigned long variable that contains a frequency I would like to display on my LCD. It's stored in MHz, with the last two digits dropped, so 142103 would be 14.2102MHz. Ideally, I'd like to to display as XX.XXX.X on my LCD where the first digit (or two) are the MHz, the next 3 are the kHz, and the last single digit represents 100's Hz. So my stored frequency of 142103 would display as 14.210.3 on the LCD.

Is there a clean way to do this without casting the number in to a string for manipulation? I can convert it to a float and get the first decimal to display nicely, but having 2 decimal's display is vexing me! I know this should be easy... Been banging my head here!

Thanks!

Steve

Hi Steve

This code will take the unsigned long frequency and format it into a string. Puts a leading zero on the MHz.

I don't have an LCD, so have simply printed the string to serial monitor.

Regards

Ray

void setup() {

  Serial.begin(115200);
  
  char buffer[9];

  const unsigned long f = 142013UL;

  unsigned int MHz = f / 10000UL;
  unsigned int kHz = (f / 10UL) % 1000;
  unsigned int Hz = f % 10; // actually, 100s of Hz
  sprintf(buffer, "%02u.%03u.%01u", MHz, kHz, Hz);

  Serial.println(buffer);

}

Thanks Ray! That's what I needed, I guess it's easiest to just do it with string manipulation functions.

I used "sprintf(buffer, "%2u.%03u.%01u", MHz, kHz, Hz); " to suppress the leading zero.

Steve

Hackscribble:
Hi Steve

This code will take the unsigned long frequency and format it into a string. Puts a leading zero on the MHz.

I don't have an LCD, so have simply printed the string to serial monitor.

Regards

Ray

void setup() {

Serial.begin(115200);
 
  char buffer[9];

const unsigned long f = 142013UL;

unsigned int MHz = f / 10000UL;
  unsigned int kHz = (f / 10UL) % 1000;
  unsigned int Hz = f % 10; // actually, 100s of Hz
  sprintf(buffer, "%02u.%03u.%01u", MHz, kHz, Hz);

Serial.println(buffer);

}

Thanks Ray,
very nice and elegant solution. IMHO this is what this forum should be about. Atta boy

I have a similar "problem".
I have user to input the frequency via terminal and eventually send the code to DDS chip to generate it.
For now I have "fixed" format "123 456 789 M" to get 123456789 Hz to convert to DDS code.
On LCD I display "123,456,789 MHz" filling in comas and completing the unit.
Little stupid , but I was after the DDS code first . Than I worry about the "B&W" - bells and whistles.
Doing stuff like this one learns a lot about converting variables.

Cheers Vaclav