You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WooCommerce价格小数格式化:添加样式并隐藏.00小数的问题求助

WooCommerce 价格小数部分上标及零小数隐藏的正确实现方案

需求

  • 为WooCommerce价格的小数部分添加类名,方便通过CSS设置为上标样式
  • 当价格小数部分为.00时,自动隐藏或移除该部分

现有代码问题

当价格设置为含税(如23%税率)时,原本应显示为4€的价格会错误显示为3.100€,10件4€商品的总价显示为39.100€。原因是浮点计算精度误差,导致小数部分被错误计算为100,且两个formatted_woocommerce_price钩子的逻辑冲突,无法正确处理零小数判断。

解决方案

合并钩子逻辑,使用精确的字符串分割方式避免浮点误差,同时保留WooCommerce原生的价格格式化规则:

PHP代码实现

add_filter( 'formatted_woocommerce_price', 'custom_wc_price_format', 20, 5 );
function custom_wc_price_format( $formatted_price, $price, $decimal_places, $decimal_separator, $thousand_separator ) {
    // 后台保持默认价格格式
    if ( is_admin() ) {
        return $formatted_price;
    }

    $num_decimals = wc_get_price_decimals();
    // 将价格转为精确字符串,避免浮点计算误差
    $price_str = number_format( $price, $num_decimals, '.', '' );
    list( $unit, $decimal ) = explode( '.', $price_str, 2 );

    // 格式化整数部分,保留千位分隔符
    $formatted_unit = number_format( (int)$unit, 0, $decimal_separator, $thousand_separator );

    // 判断小数部分是否为全零,是则只返回整数部分
    if ( ctype_digit($decimal) && (int)$decimal === 0 ) {
        return $formatted_unit;
    }

    // 返回带类名的小数部分格式
    return sprintf( '%s<span class="price-decimal">%s%s</span>', 
        $formatted_unit, 
        $decimal_separator, 
        $decimal 
    );
}

CSS上标样式

.price-decimal {
    vertical-align: super;
    font-size: 0.7em;
    margin-left: 0.1em;
}

代码说明

  1. 合并钩子逻辑:用优先级20的单一钩子替代原有两个钩子,避免逻辑冲突
  2. 精确分割价格:通过number_format将价格转为字符串后分割,彻底避免浮点精度问题
  3. 零小数判断:通过字符串校验确保只有真正的零小数价格才隐藏小数部分
  4. 保留原生格式:整数部分沿用WooCommerce的千位分隔符规则,保证风格统一

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 01:03:26