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

Number To Words Laravel Package

kwn/number-to-words

Convert numbers and currency amounts to words in PHP. Supports multiple languages via RFC 3066 identifiers, with number and currency transformers. Simple API: create transformers or use static calls to render values like 5120 as “five thousand one hundred twenty”.

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
Install via Composer:
```bash
composer require kwn/number-to-words

First Use Case: Basic Number Conversion

use NumberToWords\NumberToWords;

// Convert a number to words in English
$converter = new NumberToWords();
echo $converter->getNumberTransformer('en')->toWords(12345);
// Output: "twelve thousand three hundred forty-five"

First Use Case: Currency Conversion

// Convert currency to words (requires integer cents)
echo $converter->getCurrencyTransformer('en')->toWords(12345, 'USD');
// Output: "one hundred twenty-three dollars forty-five cents"

Where to Look First

  • Locales Table: Check README.md for supported languages/currencies (including Hungarian fixes).
  • Static Methods: Use NumberToWords::transformNumber() or NumberToWords::transformCurrency() for quick conversions.
  • Tests: Browse tests/ for edge cases and examples (Hungarian locale tests added in PR #198).

Implementation Patterns

Laravel Service Provider Integration

// app/Providers/AppServiceProvider.php
use NumberToWords\NumberToWords;

public function register()
{
    $this->app->singleton('number-to-words', function () {
        return new NumberToWords();
    });
}

Usage in Controllers/Blades:

// Controller
public function invoice(Invoice $invoice)
{
    $converter = app('number-to-words');
    $amountWords = $converter->getCurrencyTransformer('en')->toWords(
        $invoice->amount * 100,
        $invoice->currency
    );
    return view('invoice', compact('amountWords'));
}

Dynamic Locale Handling (Including Hungarian)

// Use app's locale or request locale
$locale = app()->getLocale();
$transformer = app('number-to-words')->getNumberTransformer($locale);

// Explicit Hungarian support (fixed in 3.0.1)
$hungarianTransformer = app('number-to-words')->getNumberTransformer('hu');
echo $hungarianTransformer->toWords(12345);
// Output: "tizenháromezer négyszáznegyvenöt" (correct Hungarian formatting)

Formatting Large Numbers

// Break down large numbers for readability
$number = 123456789;
$parts = [
    $transformer->toWords($number) => 'total',
    $transformer->toWords(floor($number / 1000)) => 'thousands',
];

Currency-Specific Logic

// Handle currency-specific formatting (e.g., "and" in UK English)
$ukTransformer = app('number-to-words')->getCurrencyTransformer('en_GB');
$amountWords = $ukTransformer->toWords(123456, 'GBP');
// Output: "one hundred twenty-three thousand four hundred fifty-six pounds"

Caching Transformed Values

// Cache transformed numbers/currencies
$cacheKey = "number_to_words_{$locale}_{$number}";
$words = Cache::remember($cacheKey, now()->addHours(1), function () use ($transformer, $number) {
    return $transformer->toWords($number);
});

Gotchas and Tips

Pitfalls

  1. Floating-Point Inputs:

    • Issue: Currency transformer expects integers (cents). Passing 50.99 directly fails.
    • Fix: Multiply by 100 before conversion:
      $transformer->toWords((int)($amount * 100), 'USD');
      
  2. Locale Mismatches:

    • Issue: Some locales (e.g., hu vs. hu_HU) may behave differently.
    • Fix: Use explicit locale identifiers (e.g., hu_HU for Hungarian).
    • Note: Hungarian locale was fixed in 3.0.1 to conform to standards.
  3. Negative Numbers:

    • Issue: Not all locales support negative numbers natively.
    • Fix: Handle manually:
      $number = -123;
      $words = $number < 0 ? 'minus ' . $transformer->toWords(abs($number)) : $transformer->toWords($number);
      
  4. Currency Code Sensitivity:

    • Issue: USD vs. usd may fail silently.
    • Fix: Use uppercase ISO 4217 codes (e.g., USD, EUR).
  5. Albanian Limitation:

    • Issue: Albanian transformer may fail with large numbers (>2^31).
    • Fix: Avoid for production-critical apps or patch locally.

Debugging Tips

  • Check Supported Locales: Run php artisan tinker and dump:

    $converter = new \NumberToWords\NumberToWords();
    print_r($converter->getSupportedLocales());
    

    Note: Verify Hungarian (hu) is listed and working correctly.

  • Test Edge Cases:

    $transformer->toWords(0);       // "zero"
    $transformer->toWords(1000000); // "one million"
    $transformer->toWords(999999);  // "nine hundred ninety-nine thousand nine hundred ninety-nine"
    
  • Validate Currency Codes:

    $currencyTransformer->toWords(100, 'XYZ'); // Throws exception if 'XYZ' is unsupported.
    

Extension Points

  1. Custom Locales:

    • Extend \NumberToWords\Transformers\NumberTransformer or \NumberToWords\Transformers\CurrencyTransformer for unsupported languages.
    • Example: Add app/Transformers/CustomTransformer.php and register it in the service provider.
  2. Override Default Behavior:

    • Monkey-patch the toWords() method to add custom formatting (e.g., HTML tags):
      $transformer->toWords(123, true); // Pass a flag for custom formatting
      
  3. Add Currency Support:

    • Extend \NumberToWords\Transformers\CurrencyTransformer and override getCurrencyName() and getCentName():
      class CustomCurrencyTransformer extends CurrencyTransformer {
          protected function getCurrencyName($currencyCode) {
              $names = ['CUSTOM' => 'Custom Coin'];
              return $names[$currencyCode] ?? parent::getCurrencyName($currencyCode);
          }
      }
      
  4. Performance Optimization:

    • For high-traffic apps, cache transformers:
      $this->app->singleton('currency-transformer.en', function () {
          return app('number-to-words')->getCurrencyTransformer('en');
      });
      

Laravel-Specific Quirks

  • Locale Fallback: Laravel’s app()->getLocale() may return en_US instead of en. Handle fallbacks:
    $locale = str_replace('_', '-', app()->getLocale());
    
  • Blade Directives: Create a custom Blade directive for reusable syntax:
    // app/Providers/BladeServiceProvider.php
    Blade::directive('numberToWords', function ($locale) {
        return "<?php echo app('number-to-words')->getNumberTransformer({$locale})->toWords(";
    });
    
    Usage in Blade:
    @numberToWords('hu')(12345) @endnumberToWords
    

Hungarian-Specific Notes (3.0.1)

  • Fix: The Hungarian locale now correctly formats numbers according to linguistic standards.
  • Testing: Verify with:
    $huTransformer = app('number-to-words')->getNumberTransformer('hu');
    echo $huTransformer->toWords(1000); // Should output "ezren" (not "ezer")
    
  • Edge Cases: Test with large numbers (e.g., 1000000) to ensure proper formatting.

NO_UPDATE_NEEDED would not apply here due to the meaningful Hungarian locale fix.
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky