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

Bn Php Laravel Package

zdenekdrahos/bn-php

PHP library for working with Bangla/Bengali numbers and formatting. Convert between Bengali and Latin numerals, handle digit transformations, and support localization-friendly numeric output for apps needing Bangla numeral representation.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the package via Composer:

    composer require zdenekdrahos/bn-php
    

    No additional configuration is required—it’s a drop-in replacement for PHP’s native float.

  2. First Use Case Replace float with \BN\BN for precise arithmetic:

    use BN\BN;
    
    $a = new BN('1.234567890123456789');
    $b = new BN('0.1');
    $result = $a->add($b); // No precision loss
    echo $result; // Outputs: 1.334567890123456789
    
  3. Where to Look First

    • Documentation: GitLab README (minimal but clear).
    • Source Code: Focus on BN.php for core methods (add, sub, mul, div, pow).
    • Tests: /tests directory for edge cases (e.g., very large numbers, decimal precision).

Implementation Patterns

Core Workflows

  1. Precision-Critical Calculations Use BN for financial, scientific, or high-precision math:

    $taxRate = new BN('0.20'); // 20% VAT
    $total = new BN('123.456789')->mul($taxRate)->add(new BN('123.456789'));
    
  2. Database Integration Store BN as strings in DB (e.g., decimal(38, 20)) and cast on retrieval:

    $model->amount = (new BN($request->amount))->toString();
    
  3. Laravel-Specific Patterns

    • Form Request Validation:
      use BN\BN;
      $validator->extend('bn', function ($attribute, $value, $parameters, $validator) {
          return (new BN($value))->isFinite();
      });
      
    • Model Casting:
      protected $casts = [
          'price' => BN::class,
      ];
      
  4. Performance Considerations

    • Batch Operations: Use BN::fromArray() for bulk processing:
      $numbers = BN::fromArray(['1.23', '4.56', '7.89']);
      $sum = $numbers->reduce(BN::class, 'add');
      
    • Avoid Unnecessary Objects: Reuse BN instances where possible (e.g., constants).

Integration Tips

  • API Responses: Serialize BN to strings in JSON:
    return response()->json(['total' => (string) $bnTotal]);
    
  • Logging: Log BN values as strings to avoid precision loss in logs.
  • Testing: Mock BN in unit tests to isolate logic:
    $this->partialMock(BN::class, ['add'])->willReturn(new BN('100'));
    

Gotchas and Tips

Pitfalls

  1. Type Coercion

    • Issue: Implicit casting from int/float may lose precision.
      $bn = new BN(1.23456789); // Stored as string internally, but constructor accepts floats!
      
    • Fix: Always pass BN as strings:
      $bn = new BN('1.234566789'); // Safe
      
  2. Method Chaining

    • Issue: Methods like add() return new BN instances (immutable design).
      $result = (new BN('10'))->add('5')->mul('2'); // Works, but creates intermediate objects.
      
    • Tip: Chain sparingly for readability; assign intermediate results for complex ops.
  3. Division Edge Cases

    • Issue: Division by zero throws DivisionByZeroException.
    • Fix: Validate inputs:
      if ($divisor->equals(new BN('0'))) {
          throw new \InvalidArgumentException('Division by zero');
      }
      
  4. Large Number Handling

    • Issue: Very large numbers (e.g., 1e1000) may cause memory issues.
    • Tip: Use BN::gmp() for arbitrary-precision math (requires GMP extension):
      $bn = BN::gmp('12345678901234567890');
      

Debugging Tips

  • Precision Verification: Compare BN results with PHP’s bcmath for sanity checks:
    $bnResult = (new BN('1.1'))->add('2.2');
    $bcResult = bcadd('1.1', '2.2', 10);
    assert($bnResult->toString() === $bcResult);
    
  • String Representation: Use (string) $bn or $bn->toString() for debugging—avoid var_dump (shows internal array).

Extension Points

  1. Custom Operations Extend BN by creating wrapper classes:
    class Money extends BN {
        public function format(string $currency = 'USD'): string {
            return '$' . number_format((float) $this, 2);
        }
    }
    
  2. BCMath Fallback Override BN::precision() to use bcmath settings:
    BN::setPrecision(bcscale()); // Sync with PHP's bcmath precision
    
  3. Serialization Implement JsonSerializable for custom JSON output:
    class SerializableBN extends BN implements \JsonSerializable {
        public function jsonSerialize() {
            return ['value' => $this->toString(), 'scale' => $this->scale()];
        }
    }
    

Config Quirks

  • Default Precision: BN uses 20 decimal places by default (configurable via BN::setPrecision()).
  • Locale Awareness: Avoid locale-specific decimal separators (e.g., 1,23 in some regions). Always use . for consistency.
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