PHPackages                             moahmedmish/laravel-price-formatter - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Localization &amp; i18n](/categories/localization)
4. /
5. moahmedmish/laravel-price-formatter

ActiveLibrary[Localization &amp; i18n](/categories/localization)

moahmedmish/laravel-price-formatter
===================================

A Laravel package for formatting prices based on country code and language

v1.0.3(1y ago)03MITPHPPHP ^7.3|^8.0

Since May 4Pushed 1y ago1 watchersCompare

[ Source](https://github.com/moahmedmish/laravel-price-formatter)[ Packagist](https://packagist.org/packages/moahmedmish/laravel-price-formatter)[ Docs](https://github.com/moahmedmish/laravel-price-formatter)[ RSS](/packages/moahmedmish-laravel-price-formatter/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependencies (3)Versions (5)Used By (0)

Laravel Price Formatter
=======================

[](#laravel-price-formatter)

A Laravel package for formatting prices based on country code and language. This package allows you to easily format monetary values according to different country standards and language preferences.

Features
--------

[](#features)

- Format prices based on country code and language
- Support for all world currencies with ISO 4217 codes
- Customizable formatting options (symbol position, separators, decimals)
- Support for Eastern Arabic numerals (١٢٣) for Arabic, Farsi, and Urdu languages
- Locale-based formatting using app()-&gt;getLocale()
- Accounting format for negative numbers (e.g., ($10.50) instead of -$10.50)
- Compact formatting for large numbers (e.g., 1K, 1.5M, 1B)
- Custom rounding modes (ceil, floor, half\_up, half\_down)
- Percentage formatting (e.g., 25%, 3.5%)
- Spell-out amounts in words (e.g., "Ten dollars and fifty cents")
- Dynamic currency conversion using exchange rate APIs
- Blade directives for easy templating
- Eloquent casting for money attributes
- Validation rules for money values
- Easy to use with Laravel Facade
- Fully configurable through config file
- Support for custom currency configurations

Installation
------------

[](#installation)

You can install the package via composer:

```
composer require moahmedmish/laravel-price-formatter
```

The package will automatically register its service provider.

You can publish the configuration file with:

```
php artisan vendor:publish --provider="MoahmedMish\PriceFormatter\PriceFormatterServiceProvider" --tag="config"
```

Basic Usage
-----------

[](#basic-usage)

### Format a price

[](#format-a-price)

```
// Format a price using country code and language
$formattedPrice = PriceFormatter::format(5, 'EG', 'en');
// Returns: "5 LE"

// Format a price for Arabic language
$formattedPrice = PriceFormatter::format(5, 'EG', 'ar');
// Returns: "٥ ج م" (with Eastern Arabic numerals)
```

### Format using current locale

[](#format-using-current-locale)

```
// Format a price using the current application locale
$formattedPrice = PriceFormatter::formatLocalized(10.50, 'US');
// Returns: "$10.50" (if app locale is 'en')
// Returns: "١٠٫٥٠ دولار" (if app locale is 'ar')
```

### Accounting Format

[](#accounting-format)

```
// Format negative numbers with accounting format
$formattedPrice = PriceFormatter::formatAccounting(-10.50, 'US', 'en');
// Returns: "($10.50)" instead of "-$10.50"
```

### Compact Formatting

[](#compact-formatting)

```
// Format large numbers in compact form
$formattedPrice = PriceFormatter::formatCompact(1500, 'US', 'en');
// Returns: "$1.5K"

$formattedPrice = PriceFormatter::formatCompact(1500000, 'US', 'en');
// Returns: "$1.5M"
```

### Percentage Formatting

[](#percentage-formatting)

```
// Format a value as percentage
$formattedPercentage = PriceFormatter::formatPercentage(0.255, 1);
// Returns: "25.5%"
```

### Spell Out Amounts

[](#spell-out-amounts)

```
// Convert amount to words
$amountInWords = PriceFormatter::spellOut(10.50, 'en', 'USD');
// Returns: "ten dollars and fifty cents"
```

### Currency Conversion

[](#currency-conversion)

```
// Convert from one currency to another
$convertedPrice = PriceFormatter::convert(10, 'USD', 'EUR', 'en');
// Returns the amount converted to EUR and formatted
```

### Helper Methods

[](#helper-methods)

```
// Get currency code for a country
$currencyCode = PriceFormatter::getCurrencyCode('EG');
// Returns: "EGP"

// Get currency symbol for a country and language
$currencySymbol = PriceFormatter::getCurrencySymbol('EG', 'en');
// Returns: "LE"
```

Blade Directives
----------------

[](#blade-directives)

The package provides several Blade directives for easy formatting in your views:

```
{{-- Basic formatting --}}
@money(10.50, 'US', 'en')

{{-- Localized formatting --}}
@moneyLocalized(10.50, 'US')

{{-- Accounting format --}}
@moneyAccounting(-10.50, 'US', 'en')

{{-- Compact format --}}
@moneyCompact(1500000, 'US', 'en')
```

Eloquent Casting
----------------

[](#eloquent-casting)

You can use the `MoneyCast` to automatically format money attributes in your Eloquent models:

```
use MoahmedMish\PriceFormatter\Casts\MoneyCast;

class Product extends Model
{
    protected $casts = [
        'price' => MoneyCast::class.':US,en', // Format as US dollars in English
    ];
}
```

Then when you access the attribute, it will be automatically formatted:

```
$product = Product::find(1);
echo $product->price; // Returns formatted price like "$10.50"
```

Validation Rules
----------------

[](#validation-rules)

The package provides a validation rule for money values:

```
use MoahmedMish\PriceFormatter\Rules\FormattedMoney;

$request->validate([
    'price' => ['required', new FormattedMoney('USD')],
]);
```

Configuration
-------------

[](#configuration)

The package comes with a comprehensive configuration file that allows you to customize the currency formatting for different countries and languages.

```
// config/price-formatter.php

return [
    'currencies' => [
        'EG' => [
            'code' => 'EGP',
            'formats' => [
                'en' => [
                    'symbol' => 'LE',
                    'position' => 'after',
                    'separator' => ' ',
                ],
                'ar' => [
                    'symbol' => 'ج م',
                    'position' => 'after',
                    'separator' => ' ',
                    'use_eastern_arabic_numerals' => true, // Use Eastern Arabic numerals (١٢٣)
                ],
            ],
        ],
        // Add more countries here
    ],

    'default' => [
        'symbol' => '$',
        'position' => 'before',
        'separator' => '',
        'decimal_separator' => '.',
        'thousand_separator' => ',',
        'decimals' => 2,
        'use_eastern_arabic_numerals' => false, // Set to true to use Eastern Arabic numerals by default
        'accounting_format' => false, // Set to true to use accounting format for negative numbers
        'rounding_mode' => 'half_up', // Options: 'ceil', 'floor', 'half_up', 'half_down'
    ],

    'numerals' => [
        // Automatically use Eastern Arabic numerals for these languages
        'eastern_arabic_languages' => ['ar', 'fa', 'ur'],

        // Override automatic language detection
        'force_eastern_arabic' => false, // Set to true to force Eastern Arabic numerals for all languages
        'force_western_arabic' => false, // Set to true to force Western Arabic numerals for all languages
    ],

    'locale' => [
        'use_app_locale' => true, // Set to true to automatically use app()->getLocale() for language
        'locale_to_country_map' => [
            'en' => 'US',
            'ar' => 'EG',
            'fr' => 'FR',
            // Add more mappings here
        ],
    ],

    'compact_format' => [
        'enabled' => false, // Set to true to enable compact formatting by default
        'thresholds' => [
            'thousand' => 1000,
            'million' => 1000000,
            'billion' => 1000000000,
        ],
        'symbols' => [
            'thousand' => 'K',
            'million' => 'M',
            'billion' => 'B',
        ],
        'precision' => 1, // Number of decimal places for compact format
    ],

    // Path to custom currencies configuration file
    'custom_currencies_path' => null,
];
```

### Eastern Arabic Numerals

[](#eastern-arabic-numerals)

The package supports Eastern Arabic numerals (١٢٣٤٥٦٧٨٩٠) which are commonly used in Arabic, Farsi, and Urdu languages. By default, the package will automatically use Eastern Arabic numerals when formatting prices for these languages.

You can control this behavior in several ways:

1. **Global default**: Set `use_eastern_arabic_numerals` in the default settings to `true` to use Eastern Arabic numerals for all languages by default.
2. **Language-specific**: Set `use_eastern_arabic_numerals` in the language-specific format settings to override the default behavior for that language.
3. **Force globally**: Use the `force_eastern_arabic` or `force_western_arabic` settings to override all other settings and force a specific numeral format for all languages.

### Locale-Based Formatting

[](#locale-based-formatting)

The package can automatically use the current application locale for formatting:

```
// In config/price-formatter.php
'locale' => [
    'use_app_locale' => true,
    'locale_to_country_map' => [
        'en' => 'US',
        'ar' => 'EG',
        'fr' => 'FR',
        // Add more mappings here
    ],
],
```

With this configuration, you can simply call:

```
$formattedPrice = PriceFormatter::formatLocalized(10.50);
```

And it will use the current app locale to determine the language and country for formatting.

### Custom Rounding Modes

[](#custom-rounding-modes)

The package supports different rounding modes:

- `ceil`: Always rounds up
- `floor`: Always rounds down
- `half_up`: Rounds to nearest, ties away from zero (default)
- `half_down`: Rounds to nearest, ties toward zero

```
// In config/price-formatter.php
'default' => [
    'rounding_mode' => 'half_up',
    // other settings...
],
```

### Accounting Format

[](#accounting-format-1)

For financial applications, you can use accounting format for negative numbers:

```
// In config/price-formatter.php
'default' => [
    'accounting_format' => true,
    // other settings...
],
```

This will format negative numbers with parentheses, e.g., `($10.50)` instead of `-$10.50`.

### Compact Formatting

[](#compact-formatting-1)

For large numbers, you can enable compact formatting:

```
// In config/price-formatter.php
'compact_format' => [
    'enabled' => true,
    'thresholds' => [
        'thousand' => 1000,
        'million' => 1000000,
        'billion' => 1000000000,
    ],
    'symbols' => [
        'thousand' => 'K',
        'million' => 'M',
        'billion' => 'B',
    ],
    'precision' => 1,
],
```

This will format large numbers as `1K`, `1.5M`, `2.3B`, etc.

### Customizing Currencies

[](#customizing-currencies)

The package includes all world currencies by default, but you can customize them in two ways:

1. **Using the configuration file**: Add or modify entries in the `currencies` array in the config file.
2. **Using a custom currencies JSON file**: Create a JSON file with your custom currency definitions and set the path in the config:

```
// config/price-formatter.php
'custom_currencies_path' => storage_path('app/currencies.json'),
```

The custom currencies JSON file should follow this format:

```
{
  "currencies": {
    "EGP": {
      "name": "Egyptian Pound",
      "country": "EGYPT",
      "symbol": {
        "en": "EGP",
        "ar": "ج.م",
        "native": "ج.م"
      }
    },
    "USD": {
      "name": "US Dollar",
      "country": "UNITED STATES",
      "symbol": {
        "en": "$",
        "ar": "دولار",
        "native": "$"
      }
    }
  }
}
```

Custom currency definitions will override the built-in ones with the same code.

Adding New Currencies
---------------------

[](#adding-new-currencies)

To add support for a new currency, you can either:

1. Add a new entry to the `currencies` array in the configuration file:

```
'JP' => [
    'code' => 'JPY',
    'formats' => [
        'en' => [
            'symbol' => '¥',
            'position' => 'before',
            'separator' => '',
        ],
        'ja' => [
            'symbol' => '円',
            'position' => 'after',
            'separator' => '',
        ],
        'ar' => [
            'symbol' => 'ين',
            'position' => 'after',
            'separator' => ' ',
            'use_eastern_arabic_numerals' => true,
        ],
    ],
],
```

2. Or add it to your custom currencies JSON file:

```
"JPY": {
  "name": "Yen",
  "country": "JAPAN",
  "symbol": {
    "en": "¥",
    "ja": "円",
    "ar": "ين",
    "native": "¥"
  }
}
```

Cryptocurrency Support
----------------------

[](#cryptocurrency-support)

You can add cryptocurrency support by adding entries to your configuration:

```
'currencies' => [
    'BTC' => [
        'code' => 'BTC',
        'formats' => [
            'en' => [
                'symbol' => '₿',
                'position' => 'before',
                'separator' => '',
                'decimals' => 8, // Bitcoin can have up to 8 decimal places
            ],
        ],
    ],
    'ETH' => [
        'code' => 'ETH',
        'formats' => [
            'en' => [
                'symbol' => 'Ξ',
                'position' => 'before',
                'separator' => '',
                'decimals' => 18, // Ethereum can have up to 18 decimal places
            ],
        ],
    ],
],
```

Testing
-------

[](#testing)

```
composer test
```

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

28

—

LowBetter than 54% of packages

Maintenance49

Moderate activity, may be stable

Popularity3

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity45

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 90.9% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~0 days

Total

4

Last Release

373d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/454af3b7b69b36d512c5ec8d293763d9a08c090caef7fb57e8cd64d6e5f6c46a?d=identicon)[moahmedmish](/maintainers/moahmedmish)

---

Top Contributors

[![moahmedmish](https://avatars.githubusercontent.com/u/3462355?v=4)](https://github.com/moahmedmish "moahmedmish (10 commits)")[![mohamedmish](https://avatars.githubusercontent.com/u/11056385?v=4)](https://github.com/mohamedmish "mohamedmish (1 commits)")

---

Tags

formatterlaravelcurrencylocalizationprice

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/moahmedmish-laravel-price-formatter/health.svg)

```
[![Health](https://phpackages.com/badges/moahmedmish-laravel-price-formatter/health.svg)](https://phpackages.com/packages/moahmedmish-laravel-price-formatter)
```

###  Alternatives

[kkomelin/laravel-translatable-string-exporter

Translatable String Exporter for Laravel

3291.4M10](/packages/kkomelin-laravel-translatable-string-exporter)[codezero/laravel-localized-routes

A convenient way to set up, manage and use localized routes in a Laravel app.

543638.1k4](/packages/codezero-laravel-localized-routes)[opgginc/codezero-laravel-localized-routes

A convenient way to set up, manage and use localized routes in a Laravel app.

2770.1k1](/packages/opgginc-codezero-laravel-localized-routes)[erag/laravel-lang-sync-inertia

A powerful Laravel package for syncing and managing language translations across backend and Inertia.js (Vue/React) frontends, offering effortless localization, auto-sync features, and smooth multi-language support for modern Laravel applications.

3812.2k](/packages/erag-laravel-lang-sync-inertia)[longman/laravel-multilang

Package to integrate multi language (multi locale) functionality in Laravel 5.x

5514.4k1](/packages/longman-laravel-multilang)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
