首页 > 解决方案 > 如何让 WooCommerce 变化价格具有两位小数(尾随零)?

问题描述

我有一个带有变体的产品,它由templates/single-product/add-to-cart/variation.php模板显示,它使用基于 JavaScript 的模板{{{ data.variation.display_price }}}。当我的价格以零结尾时,例如 12.50 欧元,前端的价格将显示为 12.5 欧元(没有零)。我想让价格包括尾随零。

我尝试了以下过滤器,但它不起作用。

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;
}

标签: woocommercedecimalprice

解决方案


我已经通过检查当价格有一位小数时添加一个零来修复它。

// 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;
}

推荐阅读