function price_formula_amount_profit($amazon_price, $profit_amount) { $temp_price = bcadd($amazon_price, bcdiv($profit_amount, 100, 9), 9); $temp_price = bcadd($temp_price, 0.3, 9); $ebay_price = bcdiv($temp_price, 0.871, 9); return round($ebay_price, 2); }
public static function shorten($num, $minLength, $chars = null, $affine = 0) { if (!$num) { return null; } $chars = str_split($chars ? $chars : self::$chars); $base = $divider = count($chars); if ($minLength > 1) { $num = bcadd($num, bcsub(bcpow($base, $minLength - 1), 1)); } $pos = 0; $add = $affine; $ret = array(); while ($num > 0) { $r = bcmod($num, $base); $num = bcdiv($num, $base); if (strpos($num, ".")) { $num = substr($num, 0, strpos($num, ".")); } if ($affine) { $r = ($r + $add + $pos) % $base; $add = $r; } $ret[$pos] = $chars[$r]; $pos++; } return implode("", array_reverse($ret)); }
function bcinvert($a, $n) { // Sanity check if (!is_scalar($a)) { user_error('bcinvert() expects parameter 1 to be string, ' . gettype($a) . ' given', E_USER_WARNING); return false; } if (!is_scalar($n)) { user_error('bcinvert() expects parameter 2 to be string, ' . gettype($n) . ' given', E_USER_WARNING); return false; } $u1 = $v2 = '1'; $u2 = $v1 = '0'; $u3 = $n; $v3 = $a; while (bccomp($v3, '0')) { $q0 = bcdiv($u3, $v3); $t1 = bcsub($u1, bcmul($q0, $v1)); $t2 = bcsub($u2, bcmul($q0, $v2)); $t3 = bcsub($u3, bcmul($q0, $v3)); $u1 = $v1; $u2 = $v2; $u3 = $v3; $v1 = $t1; $v2 = $t2; $v3 = $t3; } if (bccomp($u2, '0') < 0) { return bcadd($u2, $n); } else { return bcmod($u2, $n); } }
public static function checkAddress($address) { $origbase58 = $address; $dec = "0"; for ($i = 0; $i < strlen($address); $i++) { $dec = bcadd(bcmul($dec, "58", 0), strpos("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz", substr($address, $i, 1)), 0); } $address = ""; while (bccomp($dec, 0) == 1) { $dv = bcdiv($dec, "16", 0); $rem = (int) bcmod($dec, "16"); $dec = $dv; $address = $address . substr("0123456789ABCDEF", $rem, 1); } $address = strrev($address); for ($i = 0; $i < strlen($origbase58) && substr($origbase58, $i, 1) == "1"; $i++) { $address = "00" . $address; } if (strlen($address) % 2 != 0) { $address = "0" . $address; } if (strlen($address) != 50) { return false; } if (hexdec(substr($address, 0, 2)) > 0) { return false; } return substr(strtoupper(hash("sha256", hash("sha256", pack("H*", substr($address, 0, strlen($address) - 8)), true))), 0, 8) == substr($address, strlen($address) - 8); }
/** * @param Collection $paid * @param Collection $unpaid * * @return array */ public function frontpage(Collection $paid, Collection $unpaid) { $paidDescriptions = []; $paidAmount = 0; $unpaidDescriptions = []; $unpaidAmount = 0; bcscale(2); /** @var TransactionJournal $entry */ foreach ($paid as $entry) { // loop paid and create single entry: $paidDescriptions[] = $entry->description; $paidAmount = bcadd($paidAmount, $entry->amount_positive); } /** @var Bill $entry */ foreach ($unpaid as $entry) { // loop unpaid: $description = $entry[0]->name . ' (' . $entry[1]->format('jS M Y') . ')'; $amount = bcdiv(bcadd($entry[0]->amount_max, $entry[0]->amount_min), 2); $unpaidDescriptions[] = $description; $unpaidAmount = bcadd($unpaidAmount, $amount); unset($amount, $description); } $data = [['value' => $unpaidAmount, 'color' => 'rgba(53, 124, 165,0.7)', 'highlight' => 'rgba(53, 124, 165,0.9)', 'label' => trans('firefly.unpaid')], ['value' => $paidAmount, 'color' => 'rgba(0, 141, 76, 0.7)', 'highlight' => 'rgba(0, 141, 76, 0.9)', 'label' => trans('firefly.paid')]]; return $data; }
function sphPack64($v) { assert(is_numeric($v)); // x64 route if (PHP_INT_SIZE >= 8) { $i = (int) $v; return pack("NN", $i >> 32, $i & (1 << 32) - 1); } // x32 route, bcmath $x = "4294967296"; if (function_exists("bcmul")) { $h = bcdiv($v, $x, 0); $l = bcmod($v, $x); return pack("NN", (double) $h, (double) $l); // conversion to float is intentional; int would lose 31st bit } // x32 route, 15 or less decimal digits // we can use float, because its actually double and has 52 precision bits if (strlen($v) <= 15) { $f = (double) $v; $h = (int) ($f / $x); $l = (int) ($f - $x * $h); return pack("NN", $h, $l); } // x32 route, 16 or more decimal digits // well, let me know if you *really* need this die("INTERNAL ERROR: packing more than 15-digit numeric on 32-bit PHP is not implemented yet (contact support)"); }
protected static function decodeAddress($data) { $charsetHex = '0123456789ABCDEF'; $charsetB58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'; $raw = "0"; for ($i = 0; $i < strlen($data); $i++) { $current = (string) strpos($charsetB58, $data[$i]); $raw = (string) bcmul($raw, "58", 0); $raw = (string) bcadd($raw, $current, 0); } $hex = ""; while (bccomp($raw, 0) == 1) { $dv = (string) bcdiv($raw, "16", 0); $rem = (int) bcmod($raw, "16"); $raw = $dv; $hex = $hex . $charsetHex[$rem]; } $withPadding = strrev($hex); for ($i = 0; $i < strlen($data) && $data[$i] == "1"; $i++) { $withPadding = "00" . $withPadding; } if (strlen($withPadding) % 2 != 0) { $withPadding = "0" . $withPadding; } return $withPadding; }
function DateDiff($part, $begin, $end) { $diff = strtotime($end) - strtotime($begin); switch ($part) { case "y": $retval = bcdiv($diff, 60 * 60 * 24 * 365); break; case "m": $retval = bcdiv($diff, 60 * 60 * 24 * 30); break; case "w": $retval = bcdiv($diff, 60 * 60 * 24 * 7); break; case "d": $retval = bcdiv($diff, 60 * 60 * 24); break; case "h": $retval = bcdiv($diff, 60 * 60); break; case "n": $retval = bcdiv($diff, 60); break; case "s": $retval = $diff; break; } return $retval; }
function decode_username($hash) { if (!$hash) { return 'invalid_name'; } $username = ''; while ($hash) { $i = bcmod($hash, 37); $hash = bcdiv($hash, 37); if ($i == '0') { $username = '******' . $username; } else { if ($i < 27) { if (bcmod($hash, 37) == '0') { $username = chr($i + 65 - 1) . $username; } else { $username = chr($i + 97 - 1) . $username; } } else { $username = chr($i + 48 - 27) . $username; } } } return $username; }
/** * Convert a large arbitrary number between arbitrary bases * * Works the same as the php version but supports large arbitrary numbers by using BCMath * * @see http://php.net/manual/en/function.base-convert.php * @see http://php.net/manual/en/function.base-convert.php#109660 * @param string $number * @param int $frombase * @param int $tobase * @return string */ function base_convert($number, $frombase, $tobase) { if ($frombase == $tobase) { return $number; } $number = trim($number); if ($frombase != 10) { $len = strlen($number); $fromDec = 0; for ($i = 0; $i < $len; $i++) { $v = \base_convert($number[$i], $frombase, 10); $fromDec = bcadd(bcmul($fromDec, $frombase, 0), $v, 0); } } else { $fromDec = $number; } if ($tobase != 10) { $result = ''; while (bccomp($fromDec, '0', 0) > 0) { $v = intval(bcmod($fromDec, $tobase)); $result = \base_convert($v, 10, $tobase) . $result; $fromDec = bcdiv($fromDec, $tobase, 0); } } else { $result = $fromDec; } return (string) $result; }
/** * 获取两个日期的差 * * @param string $interval 返回两个日期差的间隔类型 * @param mixed $startDateTime 开始日期 * @param mixed $endDateTime 结束日期 * @return string */ public static function dateDiff($interval, $startDateTime, $endDateTime) { $diff = self::getTimeStamp($endDateTime) - self::getTimeStamp($startDateTime); $retval = 0; switch ($interval) { case "y": $retval = bcdiv($diff, 60 * 60 * 24 * 365); break; case "m": $retval = bcdiv($diff, 60 * 60 * 24 * 30); break; case "w": $retval = bcdiv($diff, 60 * 60 * 24 * 7); break; case "d": $retval = bcdiv($diff, 60 * 60 * 24); break; case "h": $retval = bcdiv($diff, 60 * 60); break; case "n": $retval = bcdiv($diff, 60); break; case "s": default: $retval = $diff; break; } return $retval; }
/** * @param $str string * @param $frombase int * @param $tobase int * * @return string * * Converts integers from base to another. */ public static function baseConvert($str, $frombase = 10, $tobase = 36) { $str = trim($str); if (intval($frombase) != 10) { $len = strlen($str); $q = 0; for ($i = 0; $i < $len; $i++) { $r = base_convert($str[$i], $frombase, 10); $q = bcadd(bcmul($q, $frombase), $r); } } else { $q = $str; } if (intval($tobase) != 10) { $s = ''; while (bccomp($q, '0', 0) > 0) { $r = intval(bcmod($q, $tobase)); $s = base_convert($r, 10, $tobase) . $s; $q = bcdiv($q, $tobase, 0); } } else { $s = $q; } return $s; }
function powmod($base, $exponent, $modulus) { if (function_exists('gmp_powm')) { // fast return gmp_strval(gmp_powm($base, $exponent, $modulus)); } if (function_exists('bi_powmod')) { // not tested return bi_sto_str(bi_powmod($base, $exponent, $modulus)); } if (function_exists('bcpowmod')) { // slow return bcpowmod($base, $exponent, $modulus); } // emulation, slow $square = bcmod($base, $modulus); $result = 1; while (bccomp($exponent, 0) > 0) { if (bcmod($exponent, 2)) { $result = bcmod(bcmul($result, $square), $modulus); } $square = bcmod(bcmul($square, $square), $modulus); $exponent = bcdiv($exponent, 2); } return $result; }
function internal_to_numstr($num, $precision = -1, $round = true) { if ($precision == -1) { $precision = 8; $tidy = true; } else { $tidy = false; } if (!is_string($num) && !is_resource($num)) { throw new Error('Coding error!', "internal_to_numstr argument has type '" . gettype($num) . "'"); } $repr = gmp_strval($num); if ($round) { if ($repr > 0) { $repr = bcadd($repr, pow(10, 8 - $precision) / 2); } else { $repr = bcsub($repr, pow(10, 8 - $precision) / 2); } } $repr = bcdiv($repr, pow(10, 8), $precision); // now tidy output... if ($tidy) { return clean_sql_numstr($repr); } return sprintf("%.{$precision}f", $repr); }
public static function makeLine($data, $do, &$errors) { //net value is unit-price * quantity if (!isset($data['tax_value'])) { //tax (in the UK at least) is dependent on the tax_rate of the item, and the tax status of the customer. //this function is a wrapper to a call to a config-dependent method $data['tax_percentage'] = calc_tax_percentage($data['tax_rate_id'], $data['tax_status_id'], $data['net_value']); $data['tax_value'] = round(bcmul($data['net_value'], $data['tax_percentage'], 4), 2); $data['tax_rate_percent'] = bcmul($data['tax_percentage'], 100); } else { $tax_rate = DataObjectFactory::Factory('TaxRate'); $tax_rate->load($data['tax_rate_id']); $data['tax_rate_percent'] = $tax_rate->percentage; } //gross value is net + tax; use bcadd to format the data $data['tax_value'] = bcadd($data['tax_value'], 0); $data['gross_value'] = bcadd($data['net_value'], $data['tax_value']); //then convert to the base currency if ($data['rate'] == 1) { $data['base_net_value'] = $data['net_value']; $data['base_tax_value'] = $data['tax_value']; $data['base_gross_value'] = $data['gross_value']; } else { $data['base_net_value'] = round(bcdiv($data['net_value'], $data['rate'], 4), 2); $data['base_tax_value'] = round(bcdiv($data['tax_value'], $data['rate'], 4), 2); $data['base_gross_value'] = round(bcadd($data['base_tax_value'], $data['base_net_value']), 2); } //and to the twin-currency $data['twin_net_value'] = round(bcmul($data['base_net_value'], $data['twin_rate'], 4), 2); $data['twin_tax_value'] = round(bcmul($data['base_tax_value'], $data['twin_rate'], 4), 2); $data['twin_gross_value'] = round(bcadd($data['twin_tax_value'], $data['twin_net_value']), 2); return DataObject::Factory($data, $errors, $do); }
/** * 生成UUID 单机使用 * @access public * @return string */ public static function uuid() { list($usec, $sec) = explode(" ", microtime(false)); $usec = (string) ($usec * 10000000); $timestamp = bcadd(bcadd(bcmul($sec, "10000000"), (string) $usec), "621355968000000000"); $ticks = bcdiv($timestamp, 10000); $maxUint = 4294967295; $high = bcdiv($ticks, $maxUint) + 0; $low = bcmod($ticks, $maxUint) - $high; $highBit = pack("N*", $high); $lowBit = pack("N*", $low); $guid = str_pad(dechex(ord($highBit[2])), 2, "0", STR_PAD_LEFT) . str_pad(dechex(ord($highBit[3])), 2, "0", STR_PAD_LEFT) . str_pad(dechex(ord($lowBit[0])), 2, "0", STR_PAD_LEFT) . str_pad(dechex(ord($lowBit[1])), 2, "0", STR_PAD_LEFT) . "-" . str_pad(dechex(ord($lowBit[2])), 2, "0", STR_PAD_LEFT) . str_pad(dechex(ord($lowBit[3])), 2, "0", STR_PAD_LEFT) . "-"; $chars = "abcdef0123456789"; for ($i = 0; $i < 4; $i++) { $guid .= $chars[mt_rand(0, 15)]; } $guid .= "-"; for ($i = 0; $i < 4; $i++) { $guid .= $chars[mt_rand(0, 15)]; } $guid .= "-"; for ($i = 0; $i < 12; $i++) { $guid .= $chars[mt_rand(0, 15)]; } return $guid; }
/** * @see http://php.net/manual/en/function.base-convert.php#106546 * * @param $numberInput * @param $fromBaseInput * @param $toBaseInput * * @return int|string */ protected static function convertBase($numberInput, $fromBaseInput, $toBaseInput) { if ($fromBaseInput == $toBaseInput) { return $numberInput; } $fromBase = str_split($fromBaseInput, 1); $toBase = str_split($toBaseInput, 1); $number = str_split($numberInput, 1); $fromLen = strlen($fromBaseInput); $toLen = strlen($toBaseInput); $numberLen = strlen($numberInput); $retval = ''; if ($toBaseInput == self::FORMAT_NUMBER) { $retval = 0; for ($i = 1; $i <= $numberLen; $i++) { $retval = bcadd($retval, bcmul(array_search($number[$i - 1], $fromBase), bcpow($fromLen, $numberLen - $i))); } return $retval; } if ($fromBaseInput != self::FORMAT_NUMBER) { $base10 = self::convertBase($numberInput, $fromBaseInput, self::FORMAT_NUMBER); } else { $base10 = $numberInput; } if ($base10 < strlen($toBaseInput)) { return $toBase[$base10]; } while ($base10 != '0') { $retval = $toBase[bcmod($base10, $toLen)] . $retval; $base10 = bcdiv($base10, $toLen, 0); } return $retval; }
function frame($row, $column, $levelinfo, $options) { $scaledtilesize = array(bcdiv(bcsub($options["framemax"][0], $options["framemin"][0]), $levelinfo["columns"]), bcdiv(bcsub($options["framemax"][1], $options["framemin"][1]), $levelinfo["rows"])); $ret["min"] = array(bcadd(bcmul($scaledtilesize[0], $column), $options["framemin"][0]), bcadd(bcmul($scaledtilesize[1], $row), $options["framemin"][1])); $ret["max"] = array(bcadd($ret["min"][0], $scaledtilesize[0]), bcadd($ret["min"][1], $scaledtilesize[1])); return $ret; }
/** * @param RequestInterface $request * @param ResponseInterface $response * * @return array */ protected function getLogData(RequestInterface $request, ResponseInterface $response = null) { $time = $this->stopwatch->stop(self::STOPWATCH_EVENT)->getDuration(); $uagent = $request->getHeader('User-Agent', '-'); $uagent = $uagent[0]; $xcache = $response && $response->hasHeaderWithValue('x-cache', 'HIT') ? 'HIT' : 'MISS'; $postDumpLimit = 200; $postData = json_encode($request->getPostParams()); if (strlen($postData) > $postDumpLimit) { $postData = substr($postData, 0, $postDumpLimit) . '...'; } $data = array(); $data[] = $xcache; $data[] = bcdiv($time, 1000, 4); // milliseconds $data[] = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '127.0.0.1'; // @todo ip is always set to 127.0.0.1 due to broken request object $data[] = $request->getMethod(); $data[] = $request->getUri(); $data[] = $response ? $response->getStatusCode() : '-'; // bytes $data[] = $response ? $response->getLength() : '-'; // bytes $data[] = sprintf('"%s"', $uagent); $data[] = $postData; return $data; }
public function div($decimal) { if (!$decimal instanceof Decimal) { $decimal = new Decimal($decimal); } return new Decimal(bcdiv($this->amount, $decimal->getAmount(), self::$scale)); }
function getStateTaxPayable() { //Arizona is a percent of federal tax rate. //However after 01-Jul-10 it changed to a straight percent of gross. $annual_income = $this->getAnnualTaxableIncome(); $rate = $this->getUserValue1(); Debug::text('Raw Rate: ' . $rate, __FILE__, __LINE__, __METHOD__, 10); //Because of the change from a percent of federal rate to a gross rate, //add some checks so if an employee's amount isn't changed we default to the closest rate. if ($rate >= 39.5) { $rate = 5.1; } elseif ($rate >= 33.1) { $rate = 4.2; } elseif ($rate >= 26.7) { $rate = 3.6; } elseif ($rate >= 24.5) { $rate = 2.7; } elseif ($rate >= 20.3) { $rate = 1.8; } elseif ($rate >= 10.7) { $rate = 1.3; } Debug::text(' Adjusted Rate: ' . $rate, __FILE__, __LINE__, __METHOD__, 10); $retval = bcmul($annual_income, bcdiv($rate, 100)); if ($retval < 0) { $retval = 0; } Debug::text('State Annual Tax Payable: ' . $retval, __FILE__, __LINE__, __METHOD__, 10); return $retval; }
function decode_base58($btcaddress) { // Compute big base58 number: $chars = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; $n = "0"; for ($i = 0; $i < strlen($btcaddress); $i++) { $p1 = strpos($chars, $btcaddress[$i]); if ($p1 === false) { return false; } $n = bcmul($n, "58"); $n = bcadd($n, (string) $p1); } // Peel off bytes to get checksum / hash / version: $checksum = ""; for ($i = 0; $i < 4; $i++) { $byte = bcmod($n, "256"); $checksum = chr((int) $byte) . $checksum; $n = bcdiv($n, "256"); } $hash = ""; for ($i = 0; $i < 20; $i++) { $byte = bcmod($n, "256"); $hash = chr((int) $byte) . $hash; $n = bcdiv($n, "256"); } $version = (int) $n; // Make sure checksum is correct: $check = hash('sha256', hash('sha256', chr($version) . $hash, true), true); if (substr($check, 0, 4) != $checksum) { return false; } return array($version, $hash, $checksum); }
public static function dateDiff($part, $begin, $end) { $diff = $end - $begin; switch ($part) { case "y": $retval = bcdiv($diff, 60 * 60 * 24 * 365); break; case "m": $retval = bcdiv($diff, 60 * 60 * 24 * 30); break; case "w": $retval = bcdiv($diff, 60 * 60 * 24 * 7); break; case "d": $retval = bcdiv($diff, 60 * 60 * 24); break; case "h": $retval = bcdiv($diff, 60 * 60); break; case "n": $retval = bcdiv($diff, 60); break; case "s": $retval = $diff; break; } return $retval; }
function bcdechex($dec, $digits = false) { $hex = ''; $positive = $dec < 0 ? false : true; while ($dec) { $hex .= dechex(abs(bcmod($dec, '16'))); $dec = bcdiv($dec, '16', 0); } if ($digits) { while (strlen($hex) < $digits) { $hex .= '0'; } } if ($positive) { return strrev($hex); } for ($i = 0; $isset($hex[$i]); $i++) { $hex[$i] = dechex(15 - hexdec($hex[$i])); } for ($i = 0; isset($hex[$i]) && $hex[$i] == 'f'; $i++) { $hex[$i] = '0'; } if (isset($hex[$i])) { $hex[$i] = dechex(hexdec($hex[$i]) + 1); } return strrev($hex); }
/** * Replace bcpowmod() * * @category PHP * @package PHP_Compat * @license LGPL - http://www.gnu.org/licenses/lgpl.html * @copyright 2004-2007 Aidan Lister <*****@*****.**>, Arpad Ray <*****@*****.**> * @link http://php.net/function.bcpowmod * @author Sara Golemon <*****@*****.**> * @version $Revision: 1.1 $ * @since PHP 5.0.0 * @require PHP 4.0.0 (user_error) */ function php_compat_bcpowmod($x, $y, $modulus, $scale = 0) { // Sanity check if (!is_scalar($x)) { user_error('bcpowmod() expects parameter 1 to be string, ' . gettype($x) . ' given', E_USER_WARNING); return false; } if (!is_scalar($y)) { user_error('bcpowmod() expects parameter 2 to be string, ' . gettype($y) . ' given', E_USER_WARNING); return false; } if (!is_scalar($modulus)) { user_error('bcpowmod() expects parameter 3 to be string, ' . gettype($modulus) . ' given', E_USER_WARNING); return false; } if (!is_scalar($scale)) { user_error('bcpowmod() expects parameter 4 to be integer, ' . gettype($scale) . ' given', E_USER_WARNING); return false; } $t = '1'; while (bccomp($y, '0')) { if (bccomp(bcmod($y, '2'), '0')) { $t = bcmod(bcmul($t, $x), $modulus); $y = bcsub($y, '1'); } $x = bcmod(bcmul($x, $x), $modulus); $y = bcdiv($y, '2'); } return $t; }
/** * @Template() */ public function statsAction() { $mmRepo = $this->get('doctrine_mongodb')->getRepository('PumukitSchemaBundle:MultimediaObject'); $seriesRepo = $this->get('doctrine_mongodb')->getRepository('PumukitSchemaBundle:series'); $counts = array('series' => $seriesRepo->countPublic(), 'mms' => $mmRepo->count(), 'hours' => bcdiv($mmRepo->countDuration(), 3600, 2)); return array('counts' => $counts); }
function fiat_and_btc_to_price($fiat, $btc, $round = 'round') { $fiat = gmp_strval($fiat); $btc = gmp_strval($btc); if (gmp_cmp($btc, "0") == 0) { return ""; } else { if ($round == 'round') { $price = bcdiv($fiat, $btc, PRICE_PRECISION + 1); return sprintf("%." . PRICE_PRECISION . "f", $price); } else { if ($round == 'down') { $price = bcdiv($fiat, $btc, PRICE_PRECISION); // echo "rounding $fiat / $btc = " . bcdiv($fiat, $btc, 8) . " down to $price<br/>\n"; return $price; } else { if ($round == 'up') { $raw = bcdiv($fiat, $btc, 8); $adjust = bcsub(bcdiv(1, pow(10, PRICE_PRECISION), 8), '0.00000001', 8); $price = bcadd($raw, $adjust, PRICE_PRECISION); // echo "rounding $fiat / $btc = $raw up to $price<br/>\n"; return $price; } else { throw new Error("Bad Argument", "fiat_and_btc_to_price() has round = '{$round}'"); } } } } }
function Extract($j){ $bigj = strval($j); $qjr = bcadd(bcmul($this->q, $bigj), $this->r); $sjt = bcadd(bcmul($this->s, $bigj), $this->t); $d = bcdiv($qjr, $sjt); return floor($d); }
function convBase($numberInput, $fromBaseInput, $toBaseInput) { if ($fromBaseInput == $toBaseInput) { return $numberInput; } $fromBase = str_split($fromBaseInput, 1); $toBase = str_split($toBaseInput, 1); $number = str_split($numberInput, 1); $fromLen = strlen($fromBaseInput); $toLen = strlen($toBaseInput); $numberLen = strlen($numberInput); $retval = ''; $base10 = ''; if ($toBaseInput == '0123456789') { $retval = 0; for ($i = 1; $i <= $numberLen; $i++) { $retval = bcadd($retval, bcmul(array_search($number[$i - 1], $fromBase), bcpow($fromLen, $numberLen - $i))); } return $retval; } if ($fromBaseInput != '0123456789') { $base10 = convBase($numberInput, $fromBaseInput, '0123456789'); } else { $base10 = $numberInput; } if ($base10 < strlen($toBaseInput)) { return $toBase[$base10]; } while ($base10 != '0') { $retval = $toBase[bcmod($base10, $toLen)] . $retval; $base10 = bcdiv($base10, $toLen, 0); } return $retval; }
/** * @param string|int|float $numerator * @param string|int|float $denominator * @param int $precision * @return string * @throws \Exception */ public static function divide($numerator, $denominator, $precision = 2) { if ($denominator == 0) { throw new \Exception('Cannot divide by zero.'); } return bcdiv($numerator, $denominator, $precision); }