A couple comments:
- my $decimals = $ARGV[1] ? $ARGV[1] : 2; won't perform as expected if the user enters 0. You will get expected behavior if you use my $decimals = defined $ARGV[1] ? $ARGV[1] : 2;. You should also swap your $float assignment.
- On the same point, if you have v5.10 or greater, you can use the 'defined or' operator (//)to do the same thing: my $decimals = $ARGV[1] // 2;
- The & is largely unnecessary in modern Perl; your code functions just fine without it.
- I'd be a little gun-shy about using the same variable name in the script level variables as in the subroutine level variables - it's easy to introduce a difficult bug.
- You can use list assignment rather than a series of shifts if you want to save a few key strokes, replacing
my $float = shift;
my $dec = shift;
with
my ($float, $dec) = @_;
This is almost entirely cosmetic in this context.
I would also point out your algorithm will still be subject to the whims of these small deviations between string and double precision representation. Consider the default case of:
#!/usr/bin/perl
use strict;
use warnings;
my $number = defined $ARGV[0] ? $ARGV[0] : 1.2549999999999999;
my $places = defined $ARGV[1] ? $ARGV[1] : 2;
printf "%.20f\n", $number;
print round( $number , $places ), "\n";
sub round {
my ($float, $decimals) = @_;
my $int_leftShiftFloat = int( $float * 10**($decimals + 1) );
my $int_Round = int( ( $int_leftShiftFloat + 5 ) / 10 );
my $float_rightShiftInt = $int_Round / 10**$decimals;
my $float_Result = $float_rightShiftInt;
return $float_Result
}
which outputs:
1.25499999999999990000
1.26
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.