0

I have a product with variations, that is being displayed by the templates/single-product/add-to-cart/variation.php template, which uses JavaScript-based templates {{{ data.variation.display_price }}}. When I have price that end with a zero, for example, € 12.50, the price on the front-end will be displayed as € 12.5 (without the zero). I want to have the price include the trailing zero.

I've tried the following filter, but it does not work.

add_filter( 'woocommerce_price_trim_zeros', 'wc_hide_trailing_zeros', 10, 1 );
function wc_hide_trailing_zeros( $trim ) {
    // set to false to show trailing zeros
    return false;
}
Arjen de Jong
  • 1,051
  • 1
  • 7
  • 15
  • What setting did you use on the general tab for Number of decimals? It seems unnecessary to set it with code. – Matts Mar 28 '19 at 08:47
  • That was default set to 2. Which is why I find it weird that it doesn't apply that setting to variation prices. – Arjen de Jong Mar 28 '19 at 08:53
  • I never had that problem with variation prices, but I'm not using € . Maybe a theme or another plugin is removing the trailing zeros. – Matts Mar 28 '19 at 09:06

1 Answers1

1

I've fixed it by checking that when the price has one decimal, add a zero.

// https://stackoverflow.com/a/2430214/3689325
function numberOfDecimals( $value ) {
    if ( (int) $value == $value ) {
        return 0;
    }
    else if ( ! is_numeric( $value ) ) {
        return false;
    }

    return strlen( $value ) - strrpos( $value, '.' ) - 1;
}

/**
 * Make sure prices have two decimals.
 */
add_filter( 'woocommerce_get_price_including_tax', 'price_two_decimals', 10, 1 );
add_filter( 'woocommerce_get_price_excluding_tax', 'price_two_decimals', 10, 1 );
function price_two_decimals( $price ) {
    if ( numberOfDecimals( $price ) === 1 ) {
        $price = number_format( $price, 2 );
        return $price;
    }

    return $price;
}
Arjen de Jong
  • 1,051
  • 1
  • 7
  • 15