简体   繁体   English

如何将销售价格四舍五入到第一位小数?

[英]How to round sale price to the first decimal digit?

I am using woocommerce 3.5.3 and Woocommerce All Discounts plugin from Orion.我正在使用 Orion 的 woocommerce 3.5.3 和 Woocommerce All Discounts 插件。 After I am applying the discounts.在我申请折扣之后。 The prices look like this: €59.90 -> €47.92, €69.90 -> €55.92.价格如下所示:59.90 欧元 -> 47.92 欧元,69.90 欧元 -> 55.92 欧元。 etc.等等。

How can I round it to the first decimal digit?如何将其四舍五入到第一个十进制数字?

I have already tried a few solutions but none work.我已经尝试了一些解决方案,但都没有奏效。 For example:例如:

function round_price_product( $price ){
    // Return rounded price
    return round( $price );
}

If we split the price in integers and fractions then we can round the fractions and use str_pad to make sure we don't loose a digit (47.9 instead of 47.90)如果我们将价格分成整数和分数,那么我们可以对分数进行四舍五入并使用 str_pad 来确保我们不会丢失数字(47.9 而不是 47.90)

Because we divide the fraction with 10 we get a new fraction that can be rounded with zero precision.因为我们将分数除以 10,所以我们得到一个新的分数,它可以以零精度舍入。
Then multiply it with 10 to get it "back" as originally.然后将其乘以 10 以使其“恢复”原样。

function round_price_product( $price ){
    // Return rounded price
    $parts = explode(".", $price);
    $parts[1] = round($parts[1]/10,0)*10;
    if($parts[1] == 100) { // round up to next integer
        $parts[0]++;
        $parts[1] = 0;
    }
    return $parts[0] . "." . str_pad($parts[1], 2, 0, STR_PAD_RIGHT);
}

echo round_price_product("47.92"); //47.90
// 47.95 -> 48.00
// 47.02 -> 47.00

https://3v4l.org/92sO1 https://3v4l.org/92sO1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM