Page 1 of 1
PHP + Maths = HURTS
Posted: Tue Sep 11, 2007 12:26 am
by stormcloud
Okay, this is going to be difficult for me to explain, so I apologise if it confuses the %&$# out of you.
i have an equation....
Code: Select all
$tmp[$row2['ship_method']]['fee'] = $rate[0] + (($w - 5) / 5) * $rate[1];
Now, I need the result to round UP to the nearest multiple of 5.
For example, if the result is 21 i need it to be 25. If the result is 15.2, i need it to be 20.
Is this at all possible?
It would REALLY make my afternoon if it is.
Thanks in advance!

Posted: Tue Sep 11, 2007 12:32 am
by jmut
Why don't you write a function that would do this for you.
using combination of ceil() and % 5.
At least I cannot think of build in function for your need.
Posted: Tue Sep 11, 2007 2:48 am
by stormcloud
I'm very new to PHP. I'm only able to modify code at the moment, not write it.
That ceil() function was EXACTLY what i needed.
Thanks for preventing the headache!!
Posted: Tue Sep 11, 2007 9:44 am
by superdezign
Just speculation. Haven't tried it.
Posted: Tue Sep 11, 2007 5:54 pm
by Ollie Saunders
Code: Select all
<?php
function ceilBy($num, $by = 10)
{
if (!is_int($by)) {
trigger_error('2nd parameter expected integer', E_USER_ERROR);
return null;
}
if (($rem = $num % $by) === 0) {
return $num;
}
return $num + $by - $rem;
}
require_once 'peewee.php';
class CeilBy_Test extends Peewee_UnitTestCase
{
public function testInt()
{
$this->assertEqual(ceilBy(20, 5), 20);
$this->assertEqual(ceilBy(21, 5), 25);
$this->assertEqual(ceilBy(24, 5), 25);
}
public function testNonIntHandle()
{
$this->expectError('2nd parameter expected integer', E_USER_ERROR);
$this->assertNull(ceilBy(1, 0.1));
}
}
Peewee_Runner::runDefined();
Posted: Tue Sep 11, 2007 9:44 pm
by superdezign
Instead of checking if $by is_int(), maybe just cast $by to an int type and then make sure it's not equal to 0 (since I know division by 0 is illegal... I'd assume modulus by 0 is as well).
Posted: Wed Sep 12, 2007 1:51 am
by Ollie Saunders
superdezign wrote:Instead of checking if $by is_int(), maybe just cast $by to an int type and then make sure it's not equal to 0 (since I know division by 0 is illegal... I'd assume modulus by 0 is as well).
I considered that but in this instance I don't think an int cast is a substitute for a failure. I prefer to
fail fast and
follow the path of least surprise.
Posted: Wed Sep 12, 2007 8:00 am
by superdezign
That makes sense, but is_int() fails on numeric strings, such as those received from form input.
Maybe... Add in an is_numeric() check inside of the is_int() failure and cast if that returns true?