Tugger the SLUGger!SLUG Mailing List Archives

Re: [coders] RubySIG Lesson Code


a php version. (yeah, i know php is considered a dirty word around here ;-) )

* ducks *

transcribed from ruby version:

#! /usr/bin/php
<?php
$amount = (float) $argv[1];

$remainder = $amount % 5;
$base_amount = $amount - $remainder;

if ($remainder > 2)
   $x = 5;
else
   $x = 0;

print $base_amount + $x . "\n";
?>

1. php, $argv is an array of command line args, starting at $argv[1]
(same reason as with python and C).
2. strings don't have methods :-)
3. could use php built in function floatval() instead of casting with (float):
$amount = floatval($argv[1]);

question: why use float and not int?

the ruby, python, and php examples don't work as expected if the
number supplied to the script is a simple float.

justin@dapper:~/$ ./round5.rb 7.4
10.0

justin@dapper:~/$ ./round5.py 7.4
10.0

justin@dapper:~/$ ./round5.php 7.4
5.4
(WTF?  in php
$remainder = $amount % 5;
returns an int, not a float...)

shorter php version that works with floats:

#! /usr/bin/php
<?php
print round((float) $argv[1] / 5) * 5 . "\n";
?>

justin@dapper:~/$ ./round5short.php 7.4
5

cheers
justin