questions

Increase WooCommerce tax calculations precision and keep displayed prices with two decimals

Rate this post

In Woocommerce settings, I have set 6 decimals in order to get more accurate tax calculation. However, I need all prices and amounts to be displayed with only 2 decimals in frontend, emails etc. I found two functions

add_filter('wc_price_args', 'custom_decimals_price_args', 10, 1);
function custom_decimals_price_args($args) {
$args['decimals'] = 2;
return $args;
}

add_filter( 'wc_get_price_decimals', 'change_prices_decimals', 20, 1 );
function change_prices_decimals($decimals){
$decimals = 2;
return $decimals;
}

What is the difference between these and which one should I use?

 

✔️Solution:

Note that WC_ROUNDING_PRECISION constant is set to 6 in WC_Woocommerce define_constants() method.

That means that WooCommerce Tax calculation precision is already set on 6 decimals.

Tax calculation precision are based on wc_get_rounding_precision() core function used in WC_Tax Class:

function wc_get_rounding_precision() {
    $precision = wc_get_price_decimals() + 2;
    if ( absint( WC_ROUNDING_PRECISION ) > $precision ) {
        $precision = absint( WC_ROUNDING_PRECISION );
    }
    return $precision;
}

As you can see WC_ROUNDING_PRECISION constant is prioritized if the displayed price decimal value + 2 is smaller than WC_ROUNDING_PRECISION constant. But as you want to keep displayed prices with 2 decimals, this requires something else.

So you should not increase displayed price decimals and not use wc_price_args or/and wc_get_price_decimals hooks, to increase precision in tax calculation.

If precision of 6 decimals is not enough and you want to get more precision:

How to get more precision on Tax calculations?

The best way to get more precision on tax calculations and keep displayed prices with 2 decimals is to edit WordPress wp_config.php file and add the following lines (where you can increase WC_ROUNDING_PRECISION constant value as you like, here the value is set to 8 for example):

// Change WooCommerce rounding precision
define('WC_ROUNDING_PRECISION', 8);

This will change WC_ROUNDING_PRECISION constant without affecting displayed price decimals.

Leave a Reply

Your email address will not be published.

Back to top button