Skip to content

Instantly share code, notes, and snippets.

@tored
Last active January 11, 2022 13:44
Show Gist options
  • Save tored/0df27b4050118420dd82b9f95d1cf474 to your computer and use it in GitHub Desktop.
Save tored/0df27b4050118420dd82b9f95d1cf474 to your computer and use it in GitHub Desktop.
PHP bcceil, bcfloor and bcround for bcmath
<?php
declare(strict_types=1);
// https://stackoverflow.com/a/1653826
// updated for PHP 8
function bcceil(string $number): string
{
if (str_contains($number, '.')) {
if (preg_match("~\.[0]+$~", $number)) {
return bcround($number, 0);
}
if ($number[0] !== '-') {
return bcadd($number, '1', 0);
}
return bcsub($number, '0', 0);
}
return $number;
}
function bcfloor(string $number): string
{
if (str_contains($number, '.')) {
if (preg_match("~\.[0]+$~", $number)) {
return bcround($number, 0);
}
if ($number[0] != '-') {
return bcadd($number, '0', 0);
}
return bcsub($number, '1', 0);
}
return $number;
}
function bcround(string $number, int $precision = 0): string
{
if (str_contains($number, '.')) {
if ($number[0] != '-') {
return bcadd($number, '0.' . str_repeat('0', $precision) . '5', $precision);
}
return bcsub($number, '0.' . str_repeat('0', $precision) . '5', $precision);
}
return $number;
}
assert(bcceil('.2') == ceil(.2));
assert(bcceil('4') == ceil(4));
assert(bcceil('4.3') == ceil(4.3));
assert(bcceil('9.999') == ceil(9.999));
assert(bcceil('-3.14') == ceil(-3.14));
assert(bcfloor('.2') == floor(.2));
assert(bcfloor('4') == floor(4));
assert(bcfloor('4.3') == floor(4.3));
assert(bcfloor('9.999') == floor(9.999));
assert(bcfloor('-3.14') == floor(-3.14));
assert(bcround('.2', 0) == number_format(.2, 0));
assert(bcround('3', 0) == number_format(3, 0));
assert(bcround('3.4', 0) == number_format(3.4, 0));
assert(bcround('3.5', 0) == number_format(3.5, 0));
assert(bcround('3.6', 0) == number_format(3.6, 0));
assert(bcround('.245', 2) == number_format(.245, 2));
assert(bcround('.255', 2) == number_format(.255, 2));
assert(bcround('1.95583', 2) == number_format(1.95583, 2));
assert(bcround('5.045', 2) == number_format(5.045, 2));
assert(bcround('5.055', 2) == number_format(5.055, 2));
assert(bcround('9.999', 2) == number_format(9.999, 2));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment