How to ceil, floor and round bcmath numbers?

前端 未结 5 1891
梦如初夏
梦如初夏 2020-11-29 08:42

I need to mimic the exact functionality of the ceil(), floor() and round() functions on bcmath numbers, I\'ve already found a very similar question but unfo

5条回答
  •  盖世英雄少女心
    2020-11-29 08:59

    Only use bcmath functions to do that:

    function bcceil($number, $precision = 0) {
        $delta = bcdiv('9', bcpow(10, $precision + 1), $precision + 1);
        $number = bcadd($number, $delta, $precision + 1);
        $number = bcadd($number, '0', $precision);
        return $number;
    }
    
    function bcfloor($number, $precision = 0) {
        $number = bcadd($number, '0', $precision);
        return $number;
    }
    

    For test:

    $numbers = [
        '1', '1.1', '1.4', '1.5', '1.9',
        '1.01', '1.09', '1.10', '1.19', '1.90', '1.99',
        '2'
    ];
    
    foreach ($numbers as $n) {
        printf("%s (ceil)--> %s\n", $n, bcceil($n, 1));
    }
    
    printf("\n");
    
    foreach ($numbers as $n) {
        printf("%s (floor)--> %s\n", $n, bcfloor($n, 1));
    }
    

    And the test results:

    1 (ceil)--> 1.0
    1.1 (ceil)--> 1.1
    1.4 (ceil)--> 1.4
    1.5 (ceil)--> 1.5
    1.9 (ceil)--> 1.9
    1.01 (ceil)--> 1.1
    1.09 (ceil)--> 1.1
    1.10 (ceil)--> 1.1
    1.19 (ceil)--> 1.2
    1.90 (ceil)--> 1.9
    1.99 (ceil)--> 2.0
    2 (ceil)--> 2.0
    
    1 (floor)--> 1.0
    1.1 (floor)--> 1.1
    1.4 (floor)--> 1.4
    1.5 (floor)--> 1.5
    1.9 (floor)--> 1.9
    1.01 (floor)--> 1.0
    1.09 (floor)--> 1.0
    1.10 (floor)--> 1.1
    1.19 (floor)--> 1.1
    1.90 (floor)--> 1.9
    1.99 (floor)--> 1.9
    2 (floor)--> 2.0
    

提交回复
热议问题