PHP实现WooCommerce商品价格末位按0/5/9规则取整
WooCommerce 自定义分位价格取整适配方案
实现逻辑
全程保留两位小数的价格精度,基于分位整数运算避免浮点数计算误差,严格匹配给定的取整规则:
- 价格最后一位数字处于0-4区间:将末位调整为0
- 价格最后一位数字为5:保持原值不变
- 价格最后一位数字处于6-9区间:将末位调整为9
核心功能代码
/** * 自定义价格取整处理 * @param float $price 原始价格值 * @return float 取整后价格,保留两位精度 */ function custom_price_rounding( float $price ): float { // 转换为以分为单位的整数,避免浮点数精度丢失 $price_cents = (int) round( $price * 100 ); // 提取分位的最后一位数字 $last_digit = $price_cents % 10; // 按照规则计算调整值 if ( $last_digit >= 0 && $last_digit <= 4 ) { $delta = -$last_digit; } elseif ( $last_digit === 5 ) { $delta = 0; } else { $delta = 9 - $last_digit; } // 转回以元为单位的价格返回 return ( $price_cents + $delta ) / 100; } // 挂载WooCommerce全局价格过滤钩子,覆盖商品、变体、促销价的计算与显示场景 add_filter( 'woocommerce_product_get_price', 'custom_price_rounding', 10, 1 ); add_filter( 'woocommerce_product_get_regular_price', 'custom_price_rounding', 10, 1 ); add_filter( 'woocommerce_product_get_sale_price', 'custom_price_rounding', 10, 1 ); add_filter( 'woocommerce_product_variation_get_price', 'custom_price_rounding', 10, 1 ); add_filter( 'woocommerce_product_variation_get_regular_price', 'custom_price_rounding', 10, 1 ); add_filter( 'woocommerce_product_variation_get_sale_price', 'custom_price_rounding', 10, 1 ); // 适配购物车页面的价格显示 add_filter( 'woocommerce_cart_item_price', function( $price_html, $cart_item ) { $adjusted_price = custom_price_rounding( $cart_item['data']->get_price() ); return wc_price( $adjusted_price ); }, 10, 2 );
效果验证
完全匹配需求示例的取整结果:
- 原价$23.12:转换为2312分,末位2处于0-4区间,调整为2310分,最终返回$23.10
- 原价$39.45:转换为3945分,末位5保持不变,最终返回$39.45
- 原价$4.26:转换为426分,末位6处于6-9区间,调整为429分,最终返回$4.29
内容的提问来源于stack exchange,提问作者Joborobo
相关产品推荐
相关产品推荐

