I am looking to round the last digit of product prices in WooCommerce with a PHP function, based on 3 rules. Price has to include cents and it does not matter if it gets rounded up or down.
If end between 0 and 4, change to 0
If end in 5, no change and stays at 5
If end between 6 and 9, change to 9
For example:
A price of $23.12 will be rounded to $23.10
A price of 39.45 will be rounded to $39.45
A price of $4.26 will be rounded to $4.29
Currently using the following code but it only rounds to a whole number.
function my_rounding_function( $price ) {
$price = round( $price );
return $price;
}
Any help would be very much appreciated! 🙂
2
Answers
Try this. Using the BC math functions, this will guard against rounding errors. Updated to truncate (round) thousands first.
Outputs:
Code: