Skip to content

Instantly share code, notes, and snippets.

@bredmor
Last active December 4, 2020 13:26
Show Gist options
  • Save bredmor/2557a0148c97ca7c3c6d3005753de0cb to your computer and use it in GitHub Desktop.
Save bredmor/2557a0148c97ca7c3c6d3005753de0cb to your computer and use it in GitHub Desktop.
BCMath functions helper for laravel
<?php
namespace App\Helpers;
/**
* Class MathHelper
* @package App\Helpers
*
* Implements negative, ceiling, floor and round functions with BCMath precision
* Credit to Matt Raines for function logic: https://stackoverflow.com/users/5024519/matt-raines
*/
class MathHelper {
/**
* Is negative?
* @param string|int $n
* @return bool
*/
public static function bcnegative($n): bool
{
return strpos($n, '-') === 0; // Is the number less than 0?
}
/**
* @param string|int $n
* @return string
*/
public static function bcceil($n): string
{
return self::bcnegative($n) ? (($v = self::bcfloor(substr($n, 1))) ? "-$v" : $v)
: bcadd(strtok($n, '.'), (string)(strtok('.') != 0));
}
/**
* @param string|int $n
* @return string
*/
public static function bcfloor($n): string
{
return self::bcnegative($n) ? '-' . self::bcceil(substr($n, 1)) : strtok($n, '.');
}
/**
* @param string|int $n
* @param int $precision
* @return string|null
*/
public static function bcround($n, int $precision = 0): ?string
{
$e = bcpow('10', (string)($precision + 1));
return bcdiv(bcadd(bcmul($n, $e, 0), (string)(self::bcnegative($n) ? -5 : 5)), $e, $precision);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment