jedstrom / php-decimal
PHP Decimal 类型实现
1.0.1
2015-11-26 17:01 UTC
Requires
- php: >=5.5.0
- ext-bcmath: *
Requires (Dev)
- phpunit/phpunit: ^5.0
This package is not auto-updated.
Last update: 2024-09-14 18:47:36 UTC
README
PHP Decimal 类型实现
一个使用 BCMath 函数执行任意精度算术运算的值对象类。
使用方法
支持的操作
以下操作目前受到支持
- 加法
- 减法
- 乘法
- 除法
源代码
$termOne = new Decimal('2', 2);
$termTwo = new Decimal('3', 0);
var_dump($termOne->add($termTwo)->getValue());
var_dump($termOne->subtract($termTwo)->getValue());
var_dump($termOne->multiply($termTwo)->getValue());
var_dump($termOne->divide($termTwo)->getValue());
// refer to Mixed Precision Calculations section
var_dump($termTwo->add($termOne)->getValue());
var_dump($termTwo->subtract($termOne)->getValue());
var_dump($termTwo->multiply($termOne)->getValue());
var_dump($termTwo->divide($termOne)->getValue());
输出
string(4) "5.00"
string(4) "-1.00"
string(4) "6.00"
string(4) "0.66"
string(4) "5"
string(4) "1"
string(4) "6"
string(4) "2"
自动精度确定
如果没有明确设置精度,将自动计算表示该值所需的精度。
源代码
$decimal = new Decimal('3.14159');
var_dump($decimal->getPrecision());
输出
int(5)
舍入方法
使用舍去零的方法进行舍入。
源代码
$termOne = new Decimal('1');
$termTwo = new Decimal('1.5');
$product = $termOne->multiply($termTwo);
var_dump($product->getValue());
输出
string(1) "2"
源代码
$termOne = new Decimal('-1');
$termTwo = new Decimal('1.5');
$product = $termOne->multiply($termTwo);
var_dump($product->getValue());
输出
string(1) "-2"
精度截断
如果明确指定了精度,但指定的值需要比指定更高的精度,则该值将被舍入到指定的精度。
源代码
$decimal = new Decimal('3.14159', 3);
var_dump($decimal->getValue());
输出
string(5) "3.142"
混合精度计算
内部以两个术语中的较大精度 + 1 进行计算,然后舍入到第一个术语的精度。
以下是一个示例
19.99 x 0.07125
内部结果是
1.424287
并且输出被舍入到第一个术语的精度(19.99 => 2)以产生
1.42
源代码
$price = new Decimal('19.99', 2);
$taxRate = new Decimal('0.07125', 5');
$tax = $price->multiply($taxRate);
var_dump($tax);
输出
string(4) "1.42"