[Chicago-talk] (no subject)

David Mertens dcmertens.perl at gmail.com
Sat Apr 28 13:27:58 PDT 2012


On Sat, Apr 28, 2012 at 3:14 PM, Alexander Danel <danel at speakeasy.net>wrote:

> 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
>

Your observation that rounding really only makes sense with a string output
is a good point that I had never quite realized. However, printf and
sprintf do not give you much control over the rounding details (which,
though esoteric, are important). In case you missed it, Michael posted that
he found a CPAN module that gave him exactly what he needed, called
Math::Decimal.

David

 -----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
>
> _______________________________________________
> Chicago-talk mailing list
> Chicago-talk at pm.org
> http://mail.pm.org/mailman/listinfo/chicago-talk
>



-- 
 "Debugging is twice as hard as writing the code in the first place.
  Therefore, if you write the code as cleverly as possible, you are,
  by definition, not smart enough to debug it." -- Brian Kernighan
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.pm.org/pipermail/chicago-talk/attachments/20120428/0d55c70f/attachment.html>


More information about the Chicago-talk mailing list