Remove decimal portion of WooCommerce price if it is zero.
A member of the Advanced WooCommerce Facebook group asked how to hide the decimal numbers when they are zero. I pointed him to my Superscript WooCommerce price decimals post as a starting point. Then I had some time and wrote some code for it.
Simple store wide method
If you wish to disable decimals throughout the store it’s easily done in WooCommerce settings. Change the 2 to 0.
Inspiration from the past
The Superscript WooCommerce price decimals used the ‘formatted_woocommerce_price‘ filter to change the displayed numbers. Having already done the research on this filter and used it I was able to write the new code quite quickly.
The core part is comparing the price to the price with the decimals removed (via the intval() function). If it’s zero then create a new number with them removed (but call number_format() to respect the potential for a thousands separator).
The code includes a comment that would show the decimals on a single product page.
Before and After
The default behaviour shows decimals for all products.
When the plugin is enabled this changes to:
The member later came back and showed that he had rewritten the code to remove decimals when they are not zero. He left in decimals when they are 0.99.
if ( $price - intval( $price ) >= 0.99 )
Obviously you can add any number of conditions to the code to determine whether to remove the decimals. You could easily limit it to certain products or product categories.