CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Intermediate:
rounding a variable?

 



Dreamer
Deleted

Mar 5, 2000, 8:00 PM

Post #1 of 5 (687 views)
rounding a variable? Can't Post

I'm back! I think I have one last problem to fix.
On my cgi program I have lots of alternatives to "fix" it, but the easiest
one would be if I could round up a variable.
Example:
<BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR>


$Zprice = $price/2;
</pre><HR></BLOCKQUOTE>
If $price is $175.00 then $Zprice=$87.50
I need at this point for $Zprice to = $88.00
(an even number).

Any help would be appreciated (again)!
TIA,
Dreamer


darian
Deleted

Mar 6, 2000, 1:12 AM

Post #2 of 5 (687 views)
Re: rounding a variable? [In reply to] Can't Post

Ok I'll take a stab at this but I have not tested it so I am going on just what I know. Let me know if this works for you.

($dollars,$cents) = split(/\./,$Zprice);
if ($cents > 49) { $dollars++; }
$Zprice = "$dollars.00";


japhy
Enthusiast

Mar 6, 2000, 6:37 AM

Post #3 of 5 (687 views)
Re: rounding a variable? [In reply to] Can't Post

If you have a number, and want to "round" it, use the int() function. This will remove the non-integer part of your number. Then, you can add 1 if the number is odd.

<BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR>


$price = int($price/2);
$price++ if $price & 1; # test for odd
</pre><HR></BLOCKQUOTE>


Dreamer
Deleted

Mar 6, 2000, 12:21 PM

Post #4 of 5 (687 views)
Re: rounding a variable? [In reply to] Can't Post

Thank you both so very much. Darian, your code did work, but instead of increasing the amount up to the next dollar, it lowered it to the last dollar. I ended up using Japhy's code, then just added a .00 at the end of $Zprice.

Darian, if you could get your code so that it could do either (round up to the next dollar) or print the actual amount, that would be cool. I played around with it, but couldn't get it to work that way.

Again, thank you two so much!
Dreamer


darian
Deleted

Mar 7, 2000, 10:26 AM

Post #5 of 5 (687 views)
Re: rounding a variable? [In reply to] Can't Post

Well I am sure I could get my code to work but I think it would be best if you stuck with japhy's code simply because it is more efficient. Using the int() does all the work in one line that I was trying to do in 3. However I am still learning and will definetly be making a note of japhy's code here.

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives