How to round/ceil/floor a bcmath number in PHP?

后端 未结 3 1159
野性不改
野性不改 2020-12-19 01:46

Is there any library function for this purpose, so I don\'t do it by hand and risk ending in TDWTF?

echo ceil(31497230840470473074370324734723042.6);

// Exp         


        
3条回答
  •  心在旅途
    2020-12-19 02:30

    OK, for my high-precision Money library, which is currently on hundreds of production sites, I had to completely rewrite this bcround functionality. Nothing I found on the entire Internet was up to code.

    Here's what I came up with:

    /**
     * Based off of https://stackoverflow.com/a/1653826/430062
     * Thanks, [Alix Axel](https://stackoverflow.com/users/89771/alix-axel)!
     *
     * @param $number
     * @param int $precision
     * @return string
     */
    function bcround($number, $precision = BCMathCalcStrategy::PRECISION)
    {
        if (strpos($number, '.') !== false) {
            if ($number[0] != '-') return bcadd($number, '0.' . str_repeat('0', $precision) . '5', $precision);
            return bcsub($number, '0.' . str_repeat('0', $precision) . '5', $precision);
        }
    
        // Pad it out to the desired precision.
        return number_format($number, $precision);
    }
    

提交回复
热议问题