Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

easy math?

by Anonymous Monk
on Nov 21, 2002 at 16:00 UTC ( [id://214800]=perlquestion: print w/replies, xml ) Need Help??

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

Replies are listed 'Best First'.
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!
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
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);

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://214800]
Approved by mpolo
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others contemplating the Monastery: (4)
As of 2024-04-20 03:00 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found