Gossamer Forum
Home : Products : DBMan : Customization :

Calculation Field ... reducing numbers

Quote Reply
Calculation Field ... reducing numbers
I'm using a Calculation mod I found on this forum, and it works perfectly, except for one of the calulations shows 12-15 decimal points when doing a percentage (2.53807106598985). Is there a way to cut it down to just 2 decimals (2.53)?

I tried reducing the max field length to just 4 characters, but that didn't make any difference.

Last edited by:

shalom777: Dec 10, 2003, 8:14 AM
Quote Reply
Re: [shalom777] Calculation Field ... reducing numbers In reply to
Here one of many Perl solutions...

$TestNum = 283.357;
printf("%.2f", $TestNum);

displays "283.36"

A real life example would be:
Code:
...please add this sales tax amount of
|; printf("%.2f", $rec{'SalesTax'}); print qq| to your total and include it with your check or money order.

Kinda somewhat related...
Another nifty trick would be for padding a field when creating space delimited text.

If the city field is 10 characters you could do:

$City = "Austin";
printf("%-10s", $City);

to display A u s t i n _ _ _ _


or you could do (without the minus sign):

$City = "Austin";
printf("%10s", $City);

to display _ _ _ _ A u s t i n
Quote Reply
Re: [Watts] Calculation Field ... reducing numbers In reply to
Thanks for the info. I'm rather new to the CGI world ... how would I integrate that into this line in my db.cgi file:

Code:
$in{'Percentage'} = $in{'TotalSpoils'} / $in{'Gross'} * $percent;

Or is there someplace else that I need to put the code? The percentage and gross fields aren't even provided to the user when adding an record to the DB. They are calculated using other fields (Run, OverRun, StartUpWaste, RunWaste).
Quote Reply
Re: [shalom777] Calculation Field ... reducing numbers In reply to
Wherever you have:

Code:
$in{'Percentage'} = $in{'TotalSpoils'} / $in{'Gross'} * $percent;

add the extra line to it:

Code:
$in{'Percentage'} = $in{'TotalSpoils'} / $in{'Gross'} * $percent;
$in{'Percentage'} = sprintf("%.2f", $in{'Percentage'});

And from then on $in{'Percentage'} will be two decimal places. "The sprintf function works just like printf, except that it returns strings instead of printing them."

<credit>excerpted from Perl for Dummies 3rd Edition pages 138-139</credit>
Quote Reply
Re: [Watts] Calculation Field ... reducing numbers In reply to
Watts,
You are a lifesaver! Thanks for your help. Would you recommend the "Perl For Dummies" book to a newbie like me?
Quote Reply
Re: [shalom777] Calculation Field ... reducing numbers In reply to
I highly recommend any of the "for Dummies" books on just about any subject. I have quite a few and they all make for good reading.