-
Notifications
You must be signed in to change notification settings - Fork 29
Decimal
The Decimal
class has been created to make easier handling large numbers inside financial applications without precision loss.
To import the Decimal
class, you must add the following line in the header of your PHP script:
use \Litipk\BigNumbers\Decimal as Decimal;
The Decimal
class provides many static constructors.
The most generic constructor, but also the slowest one.
Decimal::create($value, $scale=null)
-
$value
: Any PHP native variable that represents a number. -
$scale
: The precision we want (measured in number of digits behind the fixed point).
Decimal::fromInteger($intValue, $scale=null)
Decimal::fromFloat($fltValue, $scale=null)
Decimal::fromString($strValue, $scale=null)
Constructs a new Decimal object based on a previous one, but changing it's $scale property.
Decimal::fromDecimal(Decimal $b, $scale=null)
Remember that all Decimal
objects are immutable, all operators return new instances rather than modify the object that called the method.
// c = a + b
$c = $a->add($b, $scale); // $a and $b are Decimal objects. $scale is optional (positive integer).
// c = a - b
$c = $a->sub($b, $scale); // $a and $b are Decimal objects. $scale is optional (positive integer).
// c = a · b
$c = $a->mul($b, $scale); // $a and $b are Decimal objects. $scale is optional (positive integer).
// c = a / b
$c = $a->div($b, $scale); // $a and $b are Decimal objects. $scale is optional (positive integer).
// c = a^b
$c = $a->pow($b, $scale); // $a and $b are Decimal objects. $scale is optional (positive integer).
If $b
is 0.5 then is preferable to use the sqrt
method rather than the pow
method.
$b = $a->sqrt($scale); // $scale is optional (positive integer).
Logarithm with base 10:
$b = $a->log10($scale); // $scale is optional (positive integer).
Absolute value (in this case,the number with positive sign):
$b = $a->abs();
Additive inverse (sign change):
$b = $a->additiveInverse();
Classic rounding, finding the closest number with given number of decimal digits:
$b = $a->round($scale); // Scale is optional (0 by default, must be a positive integer).
Floor. Finds the closest number with given decimal digits (specified by $scale
) discarding the ones above the given number:
$b = $a->floor($scale); // Scale is optional (0 by default, must be a positive integer).
Ceil. Finds the closest number with given decimal digits (specified by $scale
) discarding the ones below the given number:
$b = $a->ceil($scale); // Scale is optional (0 by default, must be a positive integer).
TODO