Perl Monk, Perl Meditation PerlMonks

### Re: Using (s)printf()

by Br'er Rabbit (Initiate)
 on Aug 31, 2016 at 13:17 UTC ( #1170879=note: print w/replies, xml ) Need Help??

Having studied the article, I, the newest monk, still can't cipher how to print two floating-point numbers so they'll align On The Decimal, so the numbers may be added properly, pencilularly. e.g., print 0.12345 and -123456.12 to align thusly (oh, please let my spaces be preserved!):
```      0.12345
-123456.12
I know I'm not the only monk that seeks this. There is that other fellow in Andalusia.

Replies are listed 'Best First'.
Re^2: Using (s)printf()
by RichardK (Parson) on Aug 31, 2016 at 18:03 UTC

Try this

perl -E 'printf("%12.4f\n",12.34)'

gives

`>     12.3400`

see the docs for sprintf for much more detail :) but in brief it's "%<length>.<dp>f"

Re^2: Using (s)printf()
by Br'er Rabbit (Initiate) on Aug 31, 2016 at 13:34 UTC
Ahhh, but Re-studying the article, the thought arises that the answer might lie with "sprintf()", using it to convert to a string which can be fed to string-processing functions to find the location of the '.' and to identify, and reserve, the parts before and after. Perhaps?

Trailing whitespace can be a bit tricky. Maybe something like:

```c:\@Work\Perl\monks>perl -wMstrict -le
"for my \$n (qw(
0.12345 -0.12345  123456.12 -123456.12  123456.12345 -123456.12345
)) {
my (\$left, \$right) = (7, 5);
my \$s = sprintf qq{%\${left}s.%-\${right}s}, split m{[.]}xms, \$n, 2;
print qq{'\$s'};
}
"
'      0.12345'
'     -0.12345'
' 123456.12   '
'-123456.12   '
' 123456.12345'
'-123456.12345'

Give a man a fish:  <%-{-{-{-<

Create A New User
Node Status?
node history
Node Type: note [id://1170879]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (7)
As of 2018-11-16 18:45 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
My code is most likely broken because:

Results (200 votes). Check out past polls.

Notices?