Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:
Greetings Perl Monks! I have a quandary. I need to have an average for certain numbers, but don't want any decimals. At most, I need two spaces for whole numbers (23) but no decimals at all (54.7). Is there a way to do this without using one of those math modules (i.e. a regex), and if not, which module should I use, and how? I'm sorry to bother you with newbie questions, but afterall, that's what I am.
Peace and Love
Re: easy math?
by cfreak (Chaplain) on Nov 21, 2002 at 16:13 UTC
|
use printf() or sprintf()
perldoc -f sprintf will give you all the details on it but here's kind of how it would be used:
my $number = 29.2;
$number = sprintf("%.0f",$number);
$number should now be '29', the first argument to sprintf (and to printf) is the format string. '%' is where you are going to insert the value, the .0f means, floating point with no decemal places.
Chris
Lobster Aliens Are attacking the world! | [reply] [d/l] [select] |
Re: easy math?
by shemp (Deacon) on Nov 21, 2002 at 17:27 UTC
|
if you use the integer pragmatic module then the division operator gives an integer quotient, dropping any decimal portion.
...
use integer;
my $quotient = 94 / 5;
print "quotient = $quotient\n";
...
this will give the output:
quotient = 18
*** note, if you want the remainder, yes like in elementary school, you can use the modulus "%" operator
| [reply] [d/l] |
Re: easy math?
by Xaositect (Friar) on Nov 22, 2002 at 00:43 UTC
|
If you just want to print it out, I'd go with cfreak's sprintf solution, but just to let you know, there is an int builtin function.
ie:
my $wholenumber = int(54.7);
| [reply] [d/l] |
|