phpwordpresswoocommercerounding

WooCommerce: Round up/down prices with 2 decimals


Our payment gateway requires us to have 2 decimals activated in WooCommerce, resulting in the price looking like this: 199.00

The .00 was easy to hide with the official fix from WooCommece

add_filter( 'woocommerce_price_trim_zeros', '__return_true' );

However, we have encountered problems with products that have a percental discount applied for example all of our product bundles.

The percental discounts make the price not end with .00 and instead random number like .15, .65 and so forth. How can we fix this so that we round up/down prices

184.15 to 184.00 184.65 to 185.00

Searched Google. Searched Stackoverflow, found some codes not working.


Solution

  • Although, you can remove decimal digits from the WooCommerce admin > General Settings. However, if it does not solve the issue, you can try using raw_woocommerce_price filter to round the product price. Following code would help do that.

    add_filter( 'raw_woocommerce_price', 'wp_raw_woocommerce_price_filter', 10, 2 );
    
    /**
     * Function for `raw_woocommerce_price` filter-hook.
     * 
     * @param float        $raw_price      Raw price.
     * @param float|string $original_price Original price as float, or empty string. Since 5.0.0.
     *
     * @return float
     */
    function wp_raw_woocommerce_price_filter( $raw_price, $original_price ){
    
        // converto non-decimal number
        return round($raw_price);
    }