【问题标题】:WooCommerce Remove Extra Zero in 3 DecimalWooCommerce 以 3 位小数删除多余的零
【发布时间】:2020-08-24 17:08:45
【问题描述】:

我使用 3 位小数,所以我的价格如下所示:
"$20.000" , "$20.050" , "$20.055"

我搜索了关于删除零小数,并找到了这个:

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

但是,它无法正常工作。因为它只删除 .000 位小数。 (20.000 美元到 20 美元)
此外,我只想从最后一个小数段中删除一个额外的 0 小数。

例如; “$20.000”到“$20.00”
“$20.050”到“$20.05”
“$20.055”不会改变

【问题讨论】:

    标签: php html wordpress woocommerce decimal


    【解决方案1】:

    您上面的过滤器(返回 true)会触发 wc_trim_zeros() function 的执行,它确实仅在价格只有 0 位小数时才会删除零。

    您需要改用formatted_woocommerce_price hook。

    以下过滤器将删除所有尾随零:

    add_filter('formatted_woocommerce_price', function($formatted_price, $price, $decimals, $decimal_separator) {
        // Need to trim 0s only if we have the decimal separator present.
        if (strpos($formatted_price, $decimal_separator) !== false) {
            $formatted_price = rtrim($formatted_price, '0');
            // After trimming trailing 0s, it may happen that the decimal separator will remain there trailing... just get rid of it, if it's the case.
            $formatted_price = rtrim($formatted_price, $decimal_separator);
        }
        return $formatted_price;
    }, 10, 4);
    

    更新:如果它是第三个和最后一个小数,下面的代码只会删除一个尾随零:

    add_filter('formatted_woocommerce_price', function($formatted_price, $price, $decimals, $decimal_separator) {
        // Need to trim 0s only if we have the decimal separator present.
        if (strpos($formatted_price, $decimal_separator) !== false) {
            $formatted_price = preg_replace('/^(\d+' . preg_quote($decimal_separator, '/' ) . '\d{2})0$/', "$1", $formatted_price);
        }
        return $formatted_price;
    }, 10, 4);
    

    免责声明:代码未试用,直接写在答案框中。

    【讨论】:

    • 是的,你是对的。 add_filter() 的第三个参数是优先级,而不是参数的数量。我已经相应地更新了代码 sn-p。
    • 当小数点分隔符设置为 . (点)。
    • 完成,但 20.000 美元变成了 20 美元。感谢 20.050 美元变成了 20.05 美元。只剩下一个问题了
    • 这个不错,但我更喜欢 20.00 美元(可以看到小数)
    • 如果您希望显示 2 位小数,为什么您的价格使用 3 位小数?
    猜你喜欢
    • 2021-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-10
    • 2013-01-09
    • 2015-08-20
    • 1970-01-01
    相关资源
    最近更新 更多