Complete.Org: Mailing Lists: Archives: discussion: October 2000:
[aclug-L] Re: Formatting numbers in Perl!
Home

[aclug-L] Re: Formatting numbers in Perl!

[Top] [All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index] [Thread Index]
To: "'discussion@xxxxxxxxx'" <discussion@xxxxxxxxx>
Subject: [aclug-L] Re: Formatting numbers in Perl!
From: "Wilner, Alden" <awilner@xxxxxxxx>
Date: Fri, 20 Oct 2000 09:06:55 -0500
Reply-to: discussion@xxxxxxxxx

Yes I know. I'm using &^#%*&! Microsoft Outlook...

> > Steven Saner wrote:
...
> > > will print to a string. So something like:
> > > $sub_total = sprintf "%.2d", $price * $quantity;

...Except that those are floating point numbers, so you need "%f" 

.. And Mohammed Islam replied...

> > Now how about left or right justifying? Say I have the following..
> > 
> > 99.99 124.50 6780.98
> > 
> > I want them to line up like this:
> > 
> >   99.99
> >  124.50
> > 6780.98
> > 
> > Can i do this with sprintf?

...And Jeff Schaller wrote...

> Yes. You can also do it with format(), but *shiver* format is
> cryptic :)  

Well, it's not _that_ bad...

> If you know the width of your widest data, you
> can hard-code it as such:
> 
> $a=99.99;
> $b=124.50;
> $c=6780.98;
> printf "%7s\n", $a;
> printf "%7s\n", $b;
> printf "%7s\n", $c;

Actually, you don't _have_ to hard-code your width. Just find out what it
is:

#!/usr/bin/perl -w
$a=99.99;
$b=124.50;
$c=6780.98;

$max = 0;
for $i ($a,$b,$c) {                 # loop over all the numbers 
        $str = sprintf ( "%.2f", $i); # sprint as money
        $len = length ($str);         # find out how long
        $max = $len if ($len > $max); # remember longest 
}

$fmt = "%$max.2f\n";                # ...and use that in the print format.

printf $fmt, $a;
printf $fmt, $b;
printf $fmt, $c;

Now the only thing left is to 

use strict;       # ;-)


Alden Wilner
Perl-Monger wanna-be.


-- This is the discussion@xxxxxxxxx list.  To unsubscribe,
visit http://tmp2.complete.org/cgi-bin/listargate-aclug.cgi


[Prev in Thread] Current Thread [Next in Thread]
  • [aclug-L] Re: Formatting numbers in Perl!, Wilner, Alden <=