dspym82000 2019-01-09 19:57 采纳率: 100%
浏览 43

如何将销售价格舍入到第一个十进制数字?

I am using woocommerce 3.5.3 and Woocommerce All Discounts plugin from Orion. After I am applying the discounts. The prices look like this: €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 );
}
  • 写回答

1条回答 默认 最新

  • dream02008 2019-01-09 20:42
    关注

    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)

    Because we divide the fraction with 10 we get a new fraction that can be rounded with zero precision.
    Then multiply it with 10 to get it "back" as originally.

    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

    评论

报告相同问题?

悬赏问题

  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?