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

moontoast/math

PHP math utilities for Laravel and general use, offering convenient helpers for precise calculations, percentages, rounding, and numeric formatting. Lightweight and easy to integrate into apps where consistent arithmetic and number handling matter.

Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require moontoast/math
    

    No additional configuration is required—just autoload the package.

  2. First Use Case: Basic Arithmetic

    use Math\BigInteger;
    use Math\BigFloat;
    
    // Large integer operations
    $a = new BigInteger('12345678901234567890');
    $b = new BigInteger('98765432109876543210');
    $sum = $a->add($b); // BigInteger result
    
    // High-precision floating-point
    $x = new BigFloat('1.2345678901234567890');
    $y = new BigFloat('0.98765432109876543210');
    $product = $x->multiply($y); // BigFloat result
    
  3. Where to Look First

    • Documentation: GitHub README (if available) or inline PHPDoc comments.
    • Core Classes: Focus on BigInteger and BigFloat for most use cases.
    • Examples: Check the tests/ directory for real-world usage patterns.

Implementation Patterns

Common Workflows

  1. Large Number Handling

    // Avoid PHP's float precision issues
    $result = (new BigFloat('0.1'))->add(new BigFloat('0.2')); // Correctly returns 0.3
    
  2. Integration with Laravel

    • Validation: Use for financial/monetary calculations where precision matters.
      use Illuminate\Support\Facades\Validator;
      
      $validator = Validator::make($request->all(), [
          'amount' => 'required|numeric|min:0',
      ]);
      if ($validator->fails()) {
          // Use BigFloat to validate exact amounts
          $amount = new BigFloat($request->amount);
          if ($amount->compare(new BigFloat('1000.0001')) < 0) {
              // Custom logic for precise validation
          }
      }
      
  3. Database Storage

    • Store BigInteger/BigFloat as strings in DB (e.g., amount column as VARCHAR).
    • Serialize/deserialize via JSON or custom accessors:
      protected $casts = [
          'amount' => BigFloat::class,
      ];
      
  4. Performance Considerations

    • Caching: Cache repeated calculations (e.g., tax rates, currency conversions).
      $cacheKey = 'tax_rate_' . $currency;
      $taxRate = Cache::remember($cacheKey, 3600, function () {
          return new BigFloat('0.0725'); // 7.25% VAT
      });
      
  5. API Responses

    • Return BigFloat/BigInteger as strings in JSON to preserve precision:
      return response()->json([
          'total' => (string) $order->total,
      ]);
      

Gotchas and Tips

Pitfalls

  1. Type Coercion

    • Avoid implicit type conversion (e.g., BigInteger + string). Always use explicit methods:
      // Wrong: $result = $bigInt + '10'; // Throws exception
      // Right: $result = $bigInt->add(new BigInteger('10'));
      
  2. Precision Loss

    • BigFloat requires a precision parameter (default: 14 digits). Adjust for your needs:
      $highPrecision = new BigFloat('1.2345678901234567890', 20);
      
  3. Memory Usage

    • Large numbers consume significant memory. Streamline operations:
      // Avoid storing unnecessary intermediates
      $final = $a->multiply($b)->divide($c); // Chain operations
      
  4. Laravel Eloquent Quirks

    • Mass Assignment: Exclude BigFloat/BigInteger fields from $fillable if not serialized.
    • Query Builder: Use raw expressions for DB operations:
      $results = Model::whereRaw('CAST(amount AS DECIMAL(30,10)) > ?', ['1000.00'])->get();
      

Debugging Tips

  1. Comparison Issues

    • Use compare() for BigFloat/BigInteger comparisons (not ==):
      if ($a->compare($b) === 0) {
          // Equal
      }
      
  2. Serialization

    • Convert to/from strings for storage or logging:
      $stored = (string) $bigFloat;
      $restored = new BigFloat($stored);
      
  3. Error Handling

    • Catch MathException for invalid operations (e.g., division by zero):
      try {
          $result = $a->divide($b);
      } catch (MathException $e) {
          Log::error('Division error: ' . $e->getMessage());
      }
      

Extension Points

  1. Custom Operations

    • Extend BigInteger/BigFloat via traits or inheritance:
      class CustomBigFloat extends BigFloat {
          public function percentageOf(BigFloat $other): BigFloat {
              return $this->divide($other)->multiply(new BigFloat('100'));
          }
      }
      
  2. Integration with Monolog

    • Log BigFloat/BigInteger values directly:
      Log::info('Precision value', ['value' => (string) $bigFloat]);
      
  3. Testing

    • Use assertEquals() with BigFloat/BigInteger in PHPUnit:
      $this->assertEquals(
          new BigFloat('0.3'),
          (new BigFloat('0.1'))->add(new BigFloat('0.2'))
      );
      
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport