2
votes

I am Using "Change number of decimals in Woocommerce cart totals" answer code to display the total with 2 decimals. The code works fine for the displayed total in cart and checkout pages.

I would like if possible to do the same thing for the subtotal too. Any help is appreciated.

enter image description here

1

1 Answers

1
votes

To format the displayed subtotal amount with 2 decimals in cart and checkout pages use the following:

// Displayed formatted cart subtotal in cart and checkout pages
add_filter( 'woocommerce_cart_subtotal', 'filter_cart_subtotal_html', 10, 3 );
function filter_cart_subtotal_html( $cart_subtotal, $compound, $cart ) {
    $decimals = 2; // <==  <==  Set the number of decimals to be displayed

    $args = ['decimals' => strval($decimals)]; // Initializing

    if ( $compound ) {
        $cart_subtotal = wc_price( $cart->get_cart_contents_total() + $cart->get_shipping_total() + $cart->get_taxes_total( false, false ), $args );

    } elseif ( $cart->display_prices_including_tax() ) {
        $cart_subtotal = wc_price( $cart->get_subtotal() + $cart->get_subtotal_tax(), $args );

        if ( $cart->get_subtotal_tax() > 0 && ! wc_prices_include_tax() ) {
            $cart_subtotal .= ' <small class="tax_label">' . WC()->countries->inc_tax_or_vat() . '</small>';
        }
    } else {
        $cart_subtotal = wc_price( $cart->get_subtotal(), $args );

        if ( $cart->get_subtotal_tax() > 0 && wc_prices_include_tax() ) {
            $cart_subtotal .= ' <small class="tax_label">' . WC()->countries->ex_tax_or_vat() . '</small>';
        }
    }

    return $cart_subtotal;
}

Code goes in functions.php file of the active child theme (or active theme), or a plugin file. Tested and works.

Related: Change number of decimals in Woocommerce cart totals