printf doesn't do right justify

D

Daniel Cutter

I thought that printf would allways right justify numbers, unless told
to do differently (with '-'). perlfunc doesn't tell.

#!perl
use strict;
use warnings;
printf("%2.1f\n", 12.3);
printf("%2.1f\n", 4.5);
printf("%02.1f\n", 6.7);

The results are:
12.3
4.5
6.7

But I expected:
12.3
4.5
06.7

What am I missing?

perl -v says:
This is perl, v5.10.0 built for MSWin32-x86-multi-thread
It's Win XP with all the patches

Regards
Daniel Cutter
 
B

Ben Morrow

Quoth Daniel Cutter said:
I thought that printf would allways right justify numbers, unless told
to do differently (with '-'). perlfunc doesn't tell.

#!perl
use strict;
use warnings;
printf("%2.1f\n", 12.3);
printf("%2.1f\n", 4.5);
printf("%02.1f\n", 6.7);

The number before the . is the minimum total field width, not the number
of places before the decimal (yes, I think this is confusing too, but
it's more consistent with %3.5s). So you want

printf("%4.1f\n", 12.3);
printf("%4.1f\n", 4.5);
printf("%04.1f\n", 6.7);

Ben
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,535
Members
45,007
Latest member
obedient dusk

Latest Threads

Top