[VPM] always floating point?
Peter Scott
Peter at PSDT.com
Mon Mar 31 16:39:25 CST 2003
At 02:06 PM 3/31/2003 -0800, Carl B. Constantine wrote:
>I know that I can format a number into a floating point using standard
>printf statements like this: printf "\$%6.2f\n",$studTotal;
>
>However, what if I always want a number to be a floating point value
>regardless of the printf? For example, consider the following:
>
>my $rate = 7; # 7 cents per page printing
>
>print $rate/100;
>
>will print 0.07. But if I have:
>
>my $rate = 50; # 50 cents per page colour printer
>
>print $rate/100;
>
>will print: .5 unless I use printf's and format it: 0.50.
>
>How can I have it always to be 0.50 without using printf statements?
You can't.
That said, there's a special variable called $# that *could* do
it. *DON'T USE IT.* You'll hate yourself and so will anyone who looks
at your code. Besides, it's deprecated. [1]
>so I want to do this:
>
>my $cents = $rate/100;
>
>my $string = "$cents per page";
>
>print $string;
>
>would yield: 0.50 per page
my $string = sprintf "%.2f per page", $rate/100;
>This is for use in the Text::Table module, so I kind of need it like
>this or it prints .5 instead of 0.50, 0 instead of 0.00, and 0.07 as it
>should. There is a reason for it which goes into more detail and I can
>explain it better later, I'm just curious if I can do this or not.
printf() and sprintf() are the official answers.
[1] Okay, for the smart-alecs reading, yes, you could make $rate an
object and overload it's nummification op. I hope none of you were
considering foisting that on poor Carl...
--
Peter Scott
Pacific Systems Design Technologies
http://www.perldebugged.com/
More information about the Victoria-pm
mailing list