Weave 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

Decimal Calculator Bundle Laravel Package

dm/decimal-calculator-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the bundle via Composer:

    composer require dm/decimal-calculator-bundle
    

    Register the bundle in config/bundles.php (Symfony 5+):

    return [
        // ...
        Dm\DecimalCalculatorBundle\DmDecimalCalculatorBundle::class => ['all' => true],
    ];
    
  2. First Use Case Inject the service in a controller or service:

    use Dm\DecimalCalculatorBundle\Service\DecimalCalculator;
    
    class MyController extends AbstractController
    {
        public function index(DecimalCalculator $calculator)
        {
            $result = $calculator->add('123.456789', '987.654321');
            return new Response($result); // Outputs: 1111.111110
        }
    }
    
  3. Twig Integration Use the Twig filter in templates:

    {{ '123.456789'|decimal_add('987.654321') }}  {# Outputs: 1111.111110 #}
    

    Available filters/tags:

    • decimal_add, decimal_subtract, decimal_multiply, decimal_divide
    • decimal_round, decimal_ceil, decimal_floor

Implementation Patterns

Service-Level Usage

  • Precision Control Configure default precision in config/packages/dm_decimal_calculator.yaml:

    dm_decimal_calculator:
        precision: 20  # Default precision for all operations
    

    Override per operation:

    $calculator->add('1.234', '5.678', 15); // 15-decimal precision
    
  • Common Workflows

    • Financial Calculations
      $tax = $calculator->multiply($subtotal, '1.21'); // 21% tax
      $total = $calculator->add($subtotal, $tax);
      
    • Currency Conversion
      $converted = $calculator->divide($amount, '1.15'); // USD to EUR (1.15 exchange rate)
      
  • Chaining Operations Reuse the service across methods:

    class OrderService {
        public function __construct(private DecimalCalculator $calculator) {}
    
        public function calculateTotal(float $price, int $quantity, float $taxRate): string
        {
            $subtotal = $this->calculator->multiply($price, $quantity);
            $tax = $this->calculator->multiply($subtotal, $taxRate);
            return $this->calculator->add($subtotal, $tax);
        }
    }
    

Twig-Level Usage

  • Dynamic Calculations in Templates
    {% set discount = '15.5' %}
    {% set finalPrice = product.price|decimal_subtract(product.price|decimal_multiply(discount)|decimal_divide('100')) %}
    
  • Conditional Formatting
    {% if order.total|decimal_gt('1000') %}
        <p class="highlight">Eligible for free shipping!</p>
    {% endif %}
    

Integration Tips

  • Validation Layer Sanitize inputs before passing to the calculator:
    $amount = $request->input('amount');
    if (!preg_match('/^\d+(\.\d+)?$/', $amount)) {
        throw new \InvalidArgumentException('Invalid decimal format');
    }
    
  • Database Storage Store results as strings (e.g., decimal(20, 10) in MySQL) to preserve precision:
    $dbValue = $calculator->multiply('1.23456789', '9.87654321'); // Store as string
    

Gotchas and Tips

Pitfalls

  1. Precision Mismatch

    • Issue: Operations may silently truncate if precision isn’t set high enough.
    • Fix: Explicitly set precision for critical calculations:
      $calculator->add('0.1', '0.2', 20); // Avoids floating-point errors
      
  2. Twig Caching

    • Issue: Twig filters may not respect precision changes if cached.
    • Fix: Clear Twig cache after config updates:
      php bin/console cache:clear
      
  3. String vs. Float Inputs

    • Issue: Passing floats (e.g., 1.23) may lose precision.
    • Fix: Always pass values as strings:
      $calculator->add('1.23', '4.56'); // Correct
      $calculator->add(1.23, 4.56);    // Risky (float conversion)
      
  4. BCMath Dependencies

    • Issue: BCMath must be enabled in php.ini (extension=php_bcmath.dll).
    • Fix: Verify with:
      if (!extension_loaded('bcmath')) {
          throw new \RuntimeException('BCMath extension is required');
      }
      

Debugging Tips

  • Log Intermediate Results
    $step1 = $calculator->multiply('100', '1.2');
    $step2 = $calculator->add($step1, '5');
    logger()->info("Step 1: {$step1}, Step 2: {$step2}");
    
  • Test Edge Cases
    $this->assertEquals('0.0000000001', $calculator->add('0.00000000005', '0.00000000005'));
    

Extension Points

  1. Custom Precision Strategies Override the default BN-PHP implementation by extending the service:

    class CustomCalculator extends DecimalCalculator {
        protected function getPrecision(): int {
            return 30; // Custom default
        }
    }
    

    Register as a service in services.yaml:

    services:
        App\Service\CustomCalculator:
            tags: ['dm_decimal_calculator.calculator']
    
  2. Additional Operations Extend the Twig extension for custom functions:

    // src/Twig/DmDecimalCalculatorExtension.php
    public function getFunctions() {
        return [
            new \Twig\TwigFunction('decimal_percentage', [$this->calculator, 'calculatePercentage']),
        ];
    }
    
  3. Fallback for BCMath Implement a fallback (e.g., GMP) if BCMath is unavailable:

    dm_decimal_calculator:
        fallback: gmp  # Requires custom implementation
    
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.
tequilarapido/trackit
gregsphotography/site-builder-filament
cabaoctavio/laravel-query-log
gregsphotography/site-builder-components
io-digital/clickatell
snowsoft/laravel-admin
oxygen/auth
relicsoftware/barakah-payment-gateway
tobya/work-with-composer
equipc/laravel-email-validator
equipc/laravel-email-database-log
adedsec/nova-translated-labels
wazza/laravel-db-encryption
hokny/laravel-generator
vonsogt/backup
jengo/queues
jeremykenedy/laravel-observability
coleus/frame
thtg88/journalism
filagora/filagora-ai-forums