You need to enable JavaScript to run this app. Woocommerce单品价格保留3位小数其余价格保留2位小数实现咨询
优惠活动
大模型
产品
解决方案
定价
更多

Woocommerce单品价格保留3位小数其余价格保留2位小数实现咨询

WooCommerce 价格小数位数差异化设置方案

可通过WooCommerce原生过滤器钩子实现需求,无需安装额外插件,代码可直接复用:

实现效果匹配

  • 商品详情页、商品列表页的单个商品价格保留3位小数
  • 购物车、结算页的小计、税费、总计等所有汇总类价格自动四舍五入保留2位小数
  • 订单通知邮件内所有价格统一采用2位小数格式

可用实现代码

将以下代码添加到当前活跃主题的functions.php文件末尾,或自定义代码片段插件中即可生效:

// 按场景差异化设置价格显示小数位数
add_filter( 'woocommerce_price_decimals', 'custom_price_decimals_by_scene', 999 );
function custom_price_decimals_by_scene( $decimals ) {
    // 单个商品相关场景返回3位小数
    if ( is_product() || ( is_shop() && in_the_loop() ) ) {
        return 3;
    }
    // 其余所有场景默认返回2位小数
    return 2;
}

// 强制购物车汇总金额四舍五入保留2位
add_filter( 'woocommerce_calculated_total', 'custom_round_calculated_total', 999, 2 );
function custom_round_calculated_total( $total, $cart ) {
    return round( $total, 2 );
}

add_filter( 'woocommerce_cart_subtotal', 'custom_round_cart_subtotal', 999, 3 );
function custom_round_cart_subtotal( $subtotal, $compound, $cart ) {
    return wc_price( round( $cart->subtotal, 2 ) );
}

add_filter( 'woocommerce_cart_tax_total', 'custom_round_cart_tax', 999, 2 );
function custom_round_cart_tax( $tax_total, $cart ) {
    return wc_price( round( $cart->tax_total, 2 ) );
}

// 强制订单邮件内所有价格使用2位小数格式
add_filter( 'woocommerce_email_order_item_price', 'custom_email_item_price_format', 999, 4 );
function custom_email_item_price_format( $price, $order_item, $order, $plain_text ) {
    return wc_price( $order_item->get_total(), [ 'decimals' => 2 ] );
}

add_filter( 'woocommerce_email_order_subtotal', 'custom_email_subtotal_format', 999, 2 );
function custom_email_subtotal_format( $subtotal, $order ) {
    return wc_price( $order->get_subtotal(), [ 'decimals' => 2 ] );
}

add_filter( 'woocommerce_email_order_total', 'custom_email_total_format', 999, 2 );
function custom_email_total_format( $total, $order ) {
    return wc_price( $order->get_total(), [ 'decimals' => 2 ] );
}

注意事项

  • 添加代码后请清空WooCommerce缓存、浏览器缓存以及购物车数据后再测试,避免旧缓存干扰效果
  • 若主题自带自定义价格显示逻辑,请先确认主题没有覆盖WooCommerce默认的价格格式化方法,否则需要额外适配主题逻辑
  • 如需修改小数位数,直接调整代码中对应return的数字即可

内容的提问来源于stack exchange,提问作者WOWMedia

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.21 14:54:03