Zielfelder, Robert <[EMAIL PROTECTED]> wrote:
: 
: #!/opt/perl5/bin/perl
: 
: $var = "1.5";
: $var2 = sprintf("%.0f\n", $var);
: 
: print $var2;
: 
: $var3 = 1.5000001;
: $var4 = sprintf("%.0f\n", $var3);
: 
: print $var4;
: 
: 
: The first Print statement yields 1.  The second yields 2.
: I am using PERL Version 5.006 (result from command below) 
: running under HP-UX 10.20.

     That's not what I'm getting in 5.6.1 and 5.8.3 on winXP,
you'll probably have to roll your own rounding function.

sprintf '%.*f', $precision, $value + .5 * 10 ** -$precision;

    where $precision is the number of places after the decimal
you need for precision. In your case:

sprintf '%.*f', 0, $value + .5 * 10 ** -0;

    or just:

sprintf '%.0f', $value + .5;


    You would be safer with one of the Math:: modules.
Math::FixedPrecision or Math::Financial. I doubt my solution is
as flexible or as reliable.


    Here is an untested sub if your not writing a precision
critical application, but it won't port easily.

print round( 1.4999 );

sub round {
    # should work on all positive numbers
    my $value = shift;

    # default to 0 if precision omitted
    my $precision = $_[0] || 0;

    return sprintf '%.*f', $precision, $value + .5 * 10 ** -$precision;
}


HTH,

Charles K. Clarkson
-- 
Head Bottle Washer,
Clarkson Energy Homes, Inc.
Mobile Home Specialists
254 968-8328


-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>


Reply via email to