in reply to Re^2: How to use the int-function?
in thread How to use the int-function?
Starting a new day, I felt refreshed to wrestle with the rounding problem again. To get to the beef, here is my proposal to round numbers using the int-function:
I've provided to functionally identical versions of the sub, so you may pick up which one is easier for you to read.#!/usr/bin/perl my $float = $ARGV[0] ? $ARGV[0] : 1.255; my $decimals = $ARGV[1] ? $ARGV[1] : 2; print &round( $float , $decimals ) . "\n"; sub round { my $float = shift; my $decimals = shift; 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 } sub round_ { my $float = shift; my $dec = shift; return int( ( int( $float * 10**($dec + 1) ) + 5 ) / 10 ) / 10**$dec }
In the long version of the sub, I've tried to use speaking variable names and left out any comments instead.
To make a general comment on this solution, I've followed the suggestions provided yesterday by my fellow monks, and made the computation using integers to avoid the floating point hassle. What do you think about it?
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^4: How to use the int-function?
by kennethk (Abbot) on Jan 04, 2011 at 18:14 UTC |