public function Fraction::toDecimal in Fraction 7
Calculate the decimal equivalent of the fraction.
Parameters
$precision: The desired decimal precision.
$auto_precision: Boolean, whether or not the precision should be automatically calculated. This option provides more precision when you need it, and less when you don't. If set to TRUE, it will try to determine the maximum precision (this only works if the denominator is base 10). If the resulting precision is greater than $precision, it will be used instead.
Return value
string Returns the decimal equivalent of the fraction as a PHP string.
File
- ./
fraction.class.inc, line 134 - Fraction class
Class
- Fraction
- @file Fraction class
Code
public function toDecimal($precision = FRACTION_PRECISION_DEFAULT, $auto_precision = FALSE) {
// Get the numerator and denominator.
$numerator = $this
->getNumerator();
$denominator = $this
->getDenominator();
// If auto precision is on figure out the maximum precision.
if ($auto_precision) {
// If the denominator is base-10, max precision is the number of zeroes
// in the denominator.
if ($denominator % 10 == 0) {
$max_precision = strlen($denominator) - 1;
}
elseif ($denominator == 1) {
$max_precision = 0;
}
else {
$max_precision = strlen($denominator);
}
// Use the greater of the two precisions.
$precision = $max_precision > $precision ? $max_precision : $precision;
}
// Divide the numerator by the denominator (using BCMath if available).
if (function_exists('bcdiv')) {
// Divide the numerator and denominator, with extra precision.
$value = bcdiv($numerator, $denominator, $precision + 1);
// Return a decimal string rounded to the final precision.
return $this
->bcRound($value, $precision);
}
else {
return (string) round($numerator / $denominator, $precision);
}
}