[Chicago-talk] (no subject)

Alexander Danel danel at speakeasy.net
Sat Apr 28 13:14:40 PDT 2012


The correct way to round numbers in Perl is "printf()" and "sprintf()".

Note that rounding is something that makes sense to humans but not to
computers.  Computers are binary, they don't care about our decimal
concepts, unless we ask them to.  The times when decimal numbers matter is
during input (from a human) and output (for a human.)  Therefore, it is
appropriate that the Perl method for rounding is an output (or string)
function.

Alexander Danel

-----Original Message-----
From: chicago-talk-bounces+danel=speakeasy.net at pm.org
[mailto:chicago-talk-bounces+danel=speakeasy.net at pm.org] On Behalf Of
Michael Potter
Sent: Friday, April 27, 2012 8:55 PM
To: Chicago.pm chatter
Subject: [Chicago-talk] (no subject)

Monks,

I am looking for a graceful way to round numbers.

The following program
#!/bin/perl

sub myround
{
   my $src = shift;
   printf("%.2f\n", $src);
}

myround("1.335");
myround("0.335");

outputs this:
$ perl ./round.pl
1.33
0.34

I know why.  It has to do with the well known side effects of using floating
point.

What I don't know is a graceful way to round.

I would like to use something that already comes with perl and void adding
any modules.

--
potter
_______________________________________________
Chicago-talk mailing list
Chicago-talk at pm.org
http://mail.pm.org/mailman/listinfo/chicago-talk



More information about the Chicago-talk mailing list