Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Math Laravel Package

brick/math

Arbitrary-precision math for PHP. Work with big integers, decimals, and rational numbers via a clean OOP API. Optimized with GMP or BCMath when available, with automatic runtime selection. Requires PHP 8.2+ (older versions available).

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require brick/math
    

    Ensure PHP 8.2+ is used (or downgrade for older versions if needed).

  2. First Use Case:

    use Brick\Math\BigInteger;
    use Brick\Math\BigDecimal;
    
    // Arbitrary-precision integer
    $bigInt = BigInteger::of('9999999999999999999999999999999999999999999');
    
    // Arbitrary-precision decimal
    $bigDec = BigDecimal::of('9.99999999999999999999999999999999999999999999');
    
    // Perform operations
    echo $bigInt->plus(1); // 100000000000000000000000000000000000000000000
    echo $bigDec->multipliedBy(2); // 19.99999999999999999999999999999999999999999998
    
  3. Key Files to Reference:


Implementation Patterns

Core Workflows

1. Precision-Critical Calculations

  • Use Case: Financial calculations, cryptography, or scientific computations where floating-point inaccuracies are unacceptable.
  • Pattern:
    $amount = BigDecimal::of('100.00');
    $taxRate = BigDecimal::of('0.075');
    $tax = $amount->multipliedBy($taxRate);
    $total = $amount->plus($tax);
    
  • Why: Avoids floating-point rounding errors (e.g., 0.1 + 0.2 !== 0.3 in PHP).

2. Large Integer Operations

  • Use Case: Handling IDs, hashes, or large counters (e.g., database auto-increment with overflow protection).
  • Pattern:
    $id = BigInteger::of('9999999999999999999999999999999999999999999');
    $nextId = $id->plus(1); // No overflow
    
  • Tip: Use BigInteger::randomBits(256) for cryptographic randomness.

3. Fractional Arithmetic

  • Use Case: Exact rational number calculations (e.g., inventory splits, probability).
  • Pattern:
    $fraction = BigRational::of('2/3');
    $result = $fraction->dividedBy('7'); // 2/21 (exact)
    
  • Why: Avoids floating-point approximations entirely.

4. Rounding Control

  • Use Case: Financial rounding (e.g., banker’s rounding for currency).
  • Pattern:
    $price = BigDecimal::of('1.23456');
    $rounded = $price->setScale(2, RoundingMode::HalfEven); // 1.23
    
  • Key Methods: setScale(), dividedBy() with RoundingMode.

5. Chaining and Immutability

  • Use Case: Fluent APIs for readability (e.g., configuration builders).
  • Pattern:
    $result = BigInteger::of(10)
        ->multipliedBy(2)
        ->plus(5)
        ->dividedBy(3, RoundingMode::Down);
    
  • Why: Immutable objects enable thread-safe operations and predictable state.

Integration Tips

1. Validation Layer

  • Validate inputs before passing to Brick\Math to avoid NumberFormatException:
    if (!ctype_digit($input)) {
        throw new InvalidArgumentException('Input must be a digit string.');
    }
    $number = BigInteger::of($input);
    

2. Database Storage

  • Store BigInteger/BigDecimal as strings in databases (e.g., PostgreSQL numeric or bigint):
    $model->precision_value = $bigDec->toString();
    
  • Retrieve and re-instantiate:
    $bigDec = BigDecimal::of($model->precision_value);
    

3. Serialization

  • Use json_encode()/json_decode() for API responses:
    $data = ['total' => $bigDec->jsonSerialize()];
    
  • Note: BigNumber implements JsonSerializable and __toString().

4. Performance Optimization

  • Enable GMP/BCMath: Install PHP extensions for faster calculations:
    pecl install gmp bcmath
    
  • Avoid float: Never pass float directly to of(); use BigDecimal::fromFloatExact() instead.

5. Testing

  • Use BigDecimal::fromFloatExact() to test edge cases:
    $floatValue = 0.1 + 0.2; // 0.30000000000000004
    $exact = BigDecimal::fromFloatExact($floatValue);
    $this->assertEquals('0.30000000000000004', $exact->toString());
    

Gotchas and Tips

Pitfalls

1. Floating-Point Inputs

  • Issue: Passing float to of() throws InvalidArgumentException (since PHP 0.15).
  • Fix: Use BigDecimal::fromFloatExact() or cast to string:
    // Bad (throws exception)
    BigDecimal::of(0.1);
    
    // Good
    BigDecimal::of((string) 0.1); // or
    BigDecimal::fromFloatExact(0.1);
    

2. Division Behavior

  • Issue:
    • BigInteger::dividedBy() throws RoundingNecessaryException for non-integer results.
    • BigDecimal::dividedBy() requires a scale parameter.
  • Fix: Use dividedByExact() for exact divisions or specify rounding modes:
    // BigInteger (exact or round)
    $result = BigInteger::of(10)->dividedBy(3, RoundingMode::Down); // 3
    
    // BigDecimal (with scale)
    $result = BigDecimal::of(1)->dividedBy(3, 2, RoundingMode::HalfUp); // 0.33
    

3. Bitwise Operations

  • Issue: BigInteger bitwise ops (and(), or(), etc.) require non-negative operands.
  • Fix: Handle negatives explicitly:
    $a = BigInteger::of(-5);
    $b = BigInteger::of(3);
    $maskedA = $a->abs()->and($b->abs()); // Workaround
    

4. Zero Handling

  • Issue:
    • BigInteger::getLowestSetBit() returns null for zero (not -1).
    • BigDecimal::getPrecision() returns 1 for zero.
  • Fix: Check for zero first:
    if ($number->isZero()) {
        // Handle zero case
    }
    

5. Serialization Quirks

  • Issue: Serialized objects may not work across PHP versions/extensions.
  • Fix: Use toString() for storage or JSON serialization:
    $serialized = $bigDec->toString();
    $unserialized = BigDecimal::of($serialized);
    

6. Rounding Modes

  • Issue: Default rounding in sqrt() changed in 0.15 (now RoundingMode::Unnecessary).
  • Fix: Explicitly specify rounding:
    $sqrt = BigDecimal::of(2)->sqrt(RoundingMode::Down
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
ecotone/kafka
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata