leandro47 / simple-math
执行数学计算并格式化结果
v1.0.2
2022-09-10 00:03 UTC
Requires
- php: ^8.1
Requires (Dev)
- phan/phan: ^5.2
- phpunit/phpunit: ^9.5
- squizlabs/php_codesniffer: 3.*
This package is auto-updated.
Last update: 2024-09-10 04:25:15 UTC
README
简单数学计算和格式化结果。
值类型
- 数字
安装
使用 composer 安装
composer require leandro47/simple-math
数字
支持的表达式
- 求和
+ - 减法
- - 除法
/ - 乘法
*
函数
使用/示例
创建数字
use Leandro47\SimpleMath\TypeValue\Number; $value = Number::create(10); echo $value->value(); // output 10
求和值
use Leandro47\SimpleMath\TypeValue\Number; $value1 = Number::create(10.5); $value2 = Number::create(10.5); $result = $value1->sum($value2); echo $result->value(); // 21
减法值
$value1 = Number::create(10); $value2 = Number::create(11); $result = $value1->subtraction($value2); echo $result->value(); // -1
除法值
$value1 = Number::create(10); $value2 = Number::create(10); echo $value1->divider($value2)->value(); // 1;
当你尝试用0进行除法时可能会得到错误,这就是为什么需要使用带有 DivisionByZeroError 的 try catch 块。
$value1 = Number::create(10); $value2 = Number::create(0); try { $result = $value1->divider($value2)->value(); } catch (DivisionByZeroError $e) { $result = $e->getMessage(); } echo $result; // Value not to be zero
乘法值
use Leandro47\SimpleMath\TypeValue\Number; $value1 = Number::create(2); $value2 = Number::create(5); echo $value1->multiplication($value2)->value(); // 10
格式化值
use Leandro47\SimpleMath\Format\NumberFormat; $decimalSeparator = ','; $thousandSeparator = '.'; $format = NumberFormat::create($decimalSeparator, $thousandSeparator); $format->setValue(1000); echo $format->show(); // "1.000,00"
精度
如果你想要添加小数位数,只需添加一个额外的参数 $precision。
use Leandro47\SimpleMath\Format\NumberFormat; $decimalSeparator = ','; $thousandSeparator = '.'; $precision = 4; $format = NumberFormat::create($decimalSeparator, $thousandSeparator, $precision); echo $format->setValue(1000)->show(); // "1.000,0000" echo $format->setValue(1000.45895)->show(); // "1.000,4590"
符号
你还可以在数字前添加前缀,只需添加一个额外的参数 $symbol。
use Leandro47\SimpleMath\Format\NumberFormat; $decimalSeparator = ','; $thousandSeparator = '.'; $precision = 2; $symbol = 'R$'; $format = NumberFormat::create($decimalSeparator, $thousandSeparator, $precision, $symbol); echo $format->setValue(1000.5)->show(); // "R$ 1.000,50"
你可以在显示某些计算结果时添加格式。
use Leandro47\SimpleMath\Format\NumberFormat; use Leandro47\SimpleMath\TypeValue\Number; $decimalSeparator = ','; $thousandSeparator = '.'; $precision = 2; $symbol = 'R$'; $format = NumberFormat::create($decimalSeparator, $thousandSeparator, $precision, $symbol); $value1 = Number::create(10.5, $format); echo $value1->format(); // "R$ 10.50" echo $format->setValue(1000.5)->show(); // "R$ 1.000,50"
或者
$decimalSeparator = ','; $thousandSeparator = '.'; $precision = 2; $symbol = 'R$'; $format = NumberFormat::create($decimalSeparator, $thousandSeparator, $precision, $symbol); $value1 = Number::create(10.5); $value2 = Number::create(1000.5); echo $value1->multiplication($value2)->format($format); // "R$ 10.505,25"