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, i.e.
5000 -> 50
0000 -> 00If either of the least significant digits are non-zero they should be displayed, i.e.
150 -> 015
101 -> 0101It 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));
Try this:
printf("%.*d", 4-!(v%100)-!(v%10), v/(v%100?v%10?100:10:1));
精彩评论