 Home : Products : DBMan SQL : Discussion :

## Rounding Calculations

How would I round a calculation in a template in DBManSQL?

My calculation is as follows:
<%MSRP - \$Price%>

This takes "Retail Price" minus "Sales Price" and returns "YOU SAVE" value.
It does the calculation correctly, but occasionally produces a long value.
ex. \$8.72000000000001

See an example here:
http://proline2000.com/...4030304&CatID=23

I want to round to the nearest currency decimal.
ex. \$8.72

Any help would be appreciated!

Thanks,

Rick
http://www.proline2000.com
Pro-Line Direct Electronics Superstore

#### Last edited by:

rcaudio: Nov 6, 2003, 12:06 AM
Try the global template below:

sub {
my (\$val1,\$val2) = @_;
my \$value = \$val1 - \$val2;
my \$dol_str = reverse sprintf( "%.2f", \$value );
\$dol_str =~ s/(\d\d\d)/\$1./g;
\$dol_str =~ s/.\$//;
\$dol_str = \$dol_str;
return scalar reverse \$dol_str;
}

Now you can use <%format_num(\$MSRP, \$Price)%>

Hope that helps

TheStone.

B.
The global does round the "cents" as needed, except it cuts off the value to the left of the decimal point.

It displays \$.72 when it should be \$8.72

Here's the example again:
http://proline2000.com/...4030304&CatID=23

Thanks

Rick
http://www.proline2000.com
Pro-Line Direct Electronics Superstore
I think I figured it out. I added 3 percent symbols as noted in "RED" below.
This allows 3 or 4 place values to the left of the decimal point.

Let me know if this is incorrect, but it seems to be working now.

Code:
sub {
my (\$val1,\$val2) = @_;
my \$value = \$val1 - \$val2;
my \$dol_str = reverse sprintf( "%%%%.2f", \$value );
\$dol_str =~ s/(\d\d\d)/\$1./g;
\$dol_str =~ s/.\$//;
\$dol_str = \$dol_str;
return scalar reverse \$dol_str;
}

Thanks,

Rick
http://www.proline2000.com
Pro-Line Direct Electronics Superstore
One more modification that I found needed to be done.

On some items the result would be displayed as \$.123.45 (NOTE: Decimal Showing after \$ sign)

Here is the code that seems to work now:
Notice that I removed the decimal from LINE 5 that appeared after the "1" in the original code.

Code:

sub {
my (\$val1,\$val2) = @_;
my \$value = \$val1 - \$val2;
my \$dol_str = reverse sprintf( "%%%.2f", \$value );
\$dol_str =~ s/(\d\d\d)/\$1/g;
\$dol_str =~ s/.\$//;
\$dol_str = \$dol_str;
return scalar reverse \$dol_str;
}

Thanks,

Rick
http://www.proline2000.com
Pro-Line Direct Electronics Superstore