There are many PHP solutions online to round to the nearest 50 cents, however, I'm interested in rounding UP to the nearest 50 cents. Thus how would one adapt the following code to round UP to the nearest 50 cents?
add_filter('australia_post_shipping_rate', 'shipping_round_to_nearest_50cents');
function shipping_round_to_nearest_50cents($price) {
if(is_int($price)){
return $price;
}
$payprice = round($price * 2, 0)/2;
return $payprice;
}
Unfortunatly there does not appear to be any easy way to do so using PHP's built-in functions. Here is a simple function that will do so:
function roundUp50($n) {
$whole = (int) floor($n);
$frac = $n - $whole;
if( $frac >= 0.5 ) {
$whole += 1;
$frac = 0.0;
} else {
$frac = 0.5;
}
return $whole + $frac;
};
NOTE: This is not exact. A number like 2.49 will round to 2.5 but 2.499999999999999 will round to 3 (such repeating numbers can be mathmatically proven to equal the following number).
You can use this function that I found in the ceil PHP documentation. It will return the value of 1.5 if passed 1.26 in this example.
if( !function_exists('ceiling') )
{
function ceiling($number, $significance = 1)
{
return ( is_numeric($number) && is_numeric($significance) ) ? (ceil($number/$significance)*$significance) : false;
}
}
echo ceiling(1.26, 0.5); // 1.5