Pages: [1]   Go Down
Author Topic: Print minimum number of digits  (Read 505 times)
0 Members and 1 Guest are viewing this topic.
USA
Offline Offline
Full Member
***
Karma: 0
Posts: 238
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

What is the best way to "print" (Serial.print) an integer with a specified minimum number of digits (ex. printf("%03d", 1) -> 001)?
Logged

Seattle, WA USA
Online Online
Brattain Member
*****
Karma: 615
Posts: 49387
Seattle, WA USA
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Quote
What is the best way to "print" (Serial.print) an integer with a specified minimum number of digits (ex. printf("%03d", 1) -> 001)?
Use sprintf() to print to a buffer, then Serial.print() the buffer. It's really the only way. That makes it the best way automatically.
Logged

Pittsburgh, PA, USA
Offline Offline
Faraday Member
**
Karma: 98
Posts: 4808
I learn a bit every time I visit the forum.
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

if it's less than 1000, print a zero
if it's less than 100, print a zero
if it's less than 10, print a zero
print the number

but that's better done in a loop that starts with 1000 and divides by 10 until less than 10.

I've worked it to make fixed-point integers print fast.
Logged

I find it harder to express logic in English than in Code.
Sometimes an example says more than many times as many words.

USA
Offline Offline
Full Member
***
Karma: 0
Posts: 238
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Use sprintf() to print to a buffer, then Serial.print() the buffer. It's really the only way. That makes it the best way automatically.

I thought about that but I didn't thing that would be the preferred way because printf and friends (sprintf, fprintf, vsprintf, etc...) tend to use a lot of program (FLASH) space.
Logged

0
Offline Offline
Faraday Member
**
Karma: 24
Posts: 3487
20 LEDs are enough
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

Quote
but that's better done in a loop that starts with 1000 and divides by 10 until less than 10.

I would disagree here. The loop approach is harder to implement and will consume a lot more memory because the Arduino lacks hardware division. The approach with the if statements is much simpler and compiles to less instructions.

Even in case of variable digits I would stick with the if statements like so:

Code:
switch (digits) {
    case 5: { if (n<10000) { print('0'); }}
    case 4: { if (n<1000)  { print('0'); }}
    case 3: { if (n<100)   { print('0'); }}
    case 2: { if (n<10)    { print('0'); }}
}
print(n);
« Last Edit: August 01, 2012, 04:41:54 pm by Udo Klein » Logged

Check out my experiments http://blog.blinkenlight.net

Pages: [1]   Go Up
Jump to: