When dealing with a combination of round numbers and decimals for product prices on a WooCommerce store. Often, it can be desirable to hide the trailing .00
when a price is a round number. This is easily achievable through some string replacement but this can also go wrong if don’t factor in configurable parts of WooCommerce such as the number of decimal places and the decimals separator.
Fortunately, WooCommerce has functionality built right in to strip zeros from rounded decimal numbers.
Configuring WooCommerce to remove zeros from round decimals
With a single line of code, we can tell WooCommerce to always trim zeros from a price if the price has them:
By using this filter, WooCommerce will always attempt to strip zeros and the decimal from any price that is a round number. It’ll handle any configured price format such as .00
, .000
, .00000000
, ,00
etc.
Leveraging WooCommerce to remove zeros from any price
There may be times where you have a price assigned in a variable and need to strip any zeros. For this, we can just use WooCommerce’s wc_trim_zeros( $price )
function: