Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

convert a string to number and divide 2

Status
Not open for further replies.

jcarrott

Programmer
May 28, 2009
130
0
0
US
I know this is basic a stupid, am sorry.

I am retrieving a value from a table and I need to divide it by another value that I have retrieved.

The current code does not work.

Code:
# read POVAGRMTLN table
        my $stmt = "SELECT POVAGRMTLN.BASE_COST
           FROM LAWSON.POVAGRMTLN
           WHERE POVAGRMTLN.PROCURE_GROUP  = '" . $vVendGr . "' AND
                 POVAGRMTLN.ITEM           = '" . $vItem . "' AND
                 POVAGRMTLN.HOLD_FLAG      = '" . $vFlag . "'";

        my @rev = $dbh->selectrow_array($stmt);
        $field[23] = printf "%10.4f"($rev[0] / $vConv);

        print OU2 join('|', $vItem, $vConv, $field[23], "\n");

I am trying to define $rev[0] and $vConv to both be of a length of 10 and a decimal precission of 4. With that result going into $field[23]. Do I need to define each separately then do the math?
 
I tried to divide 2 strings which contain numbers, but it seems to work without problem.
For example, this code
Code:
use strict;
use warnings;

my $str01 = '3.14159';
my $str02 = '2.0';
my $res = $str01/$str02;

print "\$str01 = $str01, \$str02 = $str02, \$res=\$str01/\$str02 = $res\n";
gives this output:
Code:
c:\Work>perl str2num.pl
$str01 = 3.14159, $str02 = 2.0, $res=$str01/$str02 = 1.570795
 
I'm going to assume that all the lines leading up to the 'printf' line are working. For the calculation you're trying to do, you want to use sprintf. Something like this will probably work for you:
Code:
$field[23] = [red][b]s[/b][/red]printf "%10.4f"[red][b], [/b][/red]($rev[0] / $vConv);

Now that is going to lead to a problem with half-way-point alternation (take a look at perlfaq4 for an explanation.)

In the past, I have used a function similar to the one in the following code to do rounding. I'm sure it could be made to run faster but it's worked for me.
Code:
foreach (@arr) {
	my $temp = sprintf '%10.4f', myround($_, 4);
	print $temp, "\n";
}

sub myround {
	my ($float, $precision) = @_;
	my $capture = $precision + 1; #number of decimal places to capture
	if (m/([^.]+)(\.\d{$capture})/) {
		my ($ant, $cons) = ($1, $2);
		$cons = int($cons * 10**($precision)+0.5) * 10**(-$precision);
		$cons = $cons * -1 if $ant < 0;
		return $ant + $cons;
	} else {
		return $float;
	}
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top