Reputation:
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?
Upvotes: 2
Views: 2096
Reputation: 254378
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/andwc_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:
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.
Upvotes: 2
Reputation: 1913
wc_price_args
is used to add extra arguments to the price - it takes in raw price and it can add other stuff to it like for example a currency symbol. When get_price
is called it will include this currency symbol in the front end.
https://wp-kama.com/plugin/woocommerce/hook/wc_price_args
wc_get_price_decimals
it sets a number of decimals after the 'point' - eg. if you set it to 5, the price will look like 0.00000
https://wp-kama.com/plugin/woocommerce/function/wc_get_price_decimals
I didn't test this but it should do the job.
add_filter('wc_price_args', 'custom_decimals_price_args', 10, 1);
function custom_decimals_price_args($price, $args) {
return number_format((float)$price, 2, '.', '');
}
Alternatively, you can edit the template where your products are and format the get_price
with the number_format
above.
Let me know if this worked for you.
Upvotes: 0