collab-corp/ez-math

bcmath的简单PHP包装数学类。

v1.0.1 2022-03-21 01:31 UTC

This package is auto-updated.

Last update: 2024-09-21 06:49:06 UTC


README

Tests StyleCI

bcmath的简单PHP包装数学类。

安装

composer require collab-corp/ez-math

使用

只需用值实例化类,然后调用所需的方法。

<?php

use CollabCorp\EzMath;

$math = (new Math(20))->add(2)->get(); //22.00

//or can cast object as string instead of calling get();

echo (string)(new Math(20))->add(2); // 22.00

十进制/精度数字

默认情况下,小数位数是2,因此如果将要使用低/精确数字,请在执行操作之前确保将小数位数放大到足够高,以便bcmath函数正确计算最终结果。

# via method
$number = (new Math(3.5))->setPlaces(3);

# or via constructor's 2nd argument:
$number = new Math(3.5, 3);

# can do any operations where expected result wont exceed 3 decimal places.

$math->toDecimalPercent()->get(); // returns 0.035 instead of 0.03 had we kept the default 2 places.

方法链

您可以按需链式调用方法。

<?php

use CollabCorp\EzMath;

$math = (new Math(20))
            ->add(2)
            ->subtract(2)
            ->divide(2)
            ->setPlaces(2)
            ->get(); //10.00

设置小数位数

默认情况下,数字放大到2位小数。如果您使用更高精度的数字,可以使用setPlaces方法更改到所需的位数。

$math = (new Math(20))->setPlaces(4)->get(); //22.0000

//or you can always specify the places via the class constructor
$math = (new Math(20, 4))->get(); //20.0000

可用方法

setValue - 设置值

$math = (new Math(20,0))->add(2)->get(); //22

$math = $math->setValue(25)->get();//25.00

setPlaces - 四舍五入/放大到指定的位数

$math = (new Math(20,0))->add(2)->get(); //22

$math = $math->setPlaces(3)->get();//22.000

add - 向值添加一个数字

$math = (new Math(20))->add(2); //22.0000....

subtract - 从值中减去一个数字

$math = (new Math(20))->subtract(2)->get(); //18.0000...

divide - 用一个数字除以值

$math = (new Math(20))->divide(2)->get(); //10.00000000

multiply - 用一个数字乘以值

$math = (new Math(20))->multiply(2)->get(); //40.00000000000

modulus - 返回除法后的余数(modulus)

$math = (new Math(8))->modulus(5)->get(); //3.00000....

toDecimalPercent - 将值转换为百分比小数

$math = (new Math(3.5))->setPlaces(3)->toDecimalPercent()->get(); // 0.035

percentageOf - 获取给定百分比的数量

// get 7% of 3950
$tax = (new Math(3950))->percentageOf(7)->setPlaces(2)->get(); //276.50

squareRoot - 获取值的平方根

$math = (new Math(16))->squareRoot()->get(); // 4.00

贡献

以下方式始终欢迎贡献

  • 问题跟踪器
  • 拉取请求
  • Collab Corp Discord(根据要求发送邀请)

许可

本项目采用MIT许可证。