用于处理任意精度数字的值对象。

2.0.1 2023-06-17 15:31 UTC

This package is auto-updated.

Last update: 2024-09-22 13:06:01 UTC


README

License

概览

用于处理任意精度数字的值对象。

安装

composer require tiny-blocks/math

如何使用

该库公开了一些任意精度数字的具体实现。具体实现实现了 BigNumber 接口,该接口为相应的 BigNumbers 提供了行为。

使用 from 方法

使用 from 方法,可以从有效的数值创建一个新的 BigNumber 实例。您可以提供一个 stringfloat 值。

BigDecimal::from(value: '10');
BigDecimal::from(value: 10);

您可以通过 from 方法为对象设置一个 scale

BigDecimal::from(value: '10', scale: 2);

float 实例化的浮点值可能不安全,因为它们在设计上是不精确的,可能会导致精度损失。始终首选从 string 实例化,它支持无限数量的数字。

使用数学运算方法

加法

在此值和另一个值之间执行加法运算。

$augend = BigDecimal::from(value: 1);
$addend = BigDecimal::from(value: '1');

$result = $augend->add(addend: $addend);

$result->toString(); # 2

减法

在此值和另一个值之间执行减法运算。

$minuend = BigDecimal::from(value: 1);
$subtrahend = BigDecimal::from(value: '1');

$result = $minuend->subtract(subtrahend: $subtrahend);

$result->toString(); # 0

乘法

在此值和另一个值之间执行乘法运算。

$multiplicand = BigDecimal::from(value: 1);
$multiplier = BigDecimal::from(value: '1');

$result = $multiplicand->multiply(multiplier: $multiplier);

$result->toString(); # 1

除法

在此值和另一个值之间执行除法运算。

$dividend = BigDecimal::from(value: 1);
$divisor = BigDecimal::from(value: '1');

$result = $dividend->divide(divisor: $divisor);

$result->toString(); # 1

使用其他资源

如果您需要执行舍入,可以使用 withRounding 方法。

使用以下常量之一来指定舍入发生的 模式

  • HALF_UP: 当处于中间时,舍入到非零。

    $value = BigDecimal::from(value: 0.9950, scale: 2);
    
    $result = $value->withRounding(mode: RoundingMode::HALF_UP);
    
    $result->toString(); # 1
  • HALF_DOWN: 当处于中间时,舍入到零。

    $value = BigDecimal::from(value: 0.9950, scale: 2);
    
    $result = $value->withRounding(mode: RoundingMode::HALF_DOWN);
    
    $result->toString(); # 0.99
  • HALF_EVEN: 当处于中间时,舍入到最近的偶数。

    $value = BigDecimal::from(value: 0.9950, scale: 2);
    
    $result = $value->withRounding(mode: RoundingMode::HALF_EVEN);
    
    $result->toString(); # 1
  • HALF_ODD: 当处于中间时,舍入到最近的奇数。

    $value = BigDecimal::from(value: 0.9950, scale: 2);
    
    $result = $value->withRounding(mode: RoundingMode::HALF_ODD);
    
    $result->toString(); # 0.99

取反

有时需要将值转换为负值,在这些情况下,您可以使用 negate 方法。

$value = BigDecimal::from(value: 1);

$result = $value->negate();

$result->toString(); # -1

其他

查看其他可用资源,请参阅 BigNumber 接口。

许可协议

Math 采用 MIT 许可。

贡献

请遵循 贡献指南 以贡献到项目。