简体   繁体   中英

Printf Numerical Right Justify

I'm trying to format a number that has a value from 0 to 9,999. I would like the 2 most significant digits to always display, ie

5000 -> 50
0000 -> 00

If either of the least significant digits are non-zero they should be displayed, ie

150 -> 015
101 -> 0101

It can be done with some hackery, but can C's printf do this directly?

Yes you can use printf for this

int v = 5000;
if ((v % 100) != 0)
    printf("%04d", v);
else
    printf("%02d", v/100);

Ugly, but working as far as I can tell:

printf("%d", value / 1000);
printf("%d", (value % 1000) / 100);
if(value % 100) printf("%d", (value % 100) / 10);
if(value % 10)  printf("%d", value % 10);

I'll try to golf it some more:

printf("%02d", value / 100);
if(value % 10) printf("%02d", value % 100);
else if(value % 100) printf("%d", (value % 100) / 10);

int hi = value / 100, lo = value % 100;
printf(lo ? "%02d%0*d" : "%02d", hi, 1 + !!(lo % 10), lo % 10 ? lo : lo / 10);

printf("%d", v/(v%100?v%10?100:10:1));

尝试这个:

printf("%.*d", 4-!(v%100)-!(v%10), v/(v%100?v%10?100:10:1));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM