90 lines
2.9 KiB
PHP
90 lines
2.9 KiB
PHP
<?php
|
||
|
||
namespace App\Helpers;
|
||
|
||
class NumberHelper
|
||
{
|
||
/**
|
||
* Convert Latin digits to Persian digits.
|
||
*/
|
||
public static function toPersianDigits(string|int|float $number): string
|
||
{
|
||
$persian = ['۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹'];
|
||
$latin = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
|
||
|
||
return str_replace($latin, $persian, (string) $number);
|
||
}
|
||
|
||
/**
|
||
* Convert Persian/Arabic digits to Latin digits.
|
||
*/
|
||
public static function toLatinDigits(string $number): string
|
||
{
|
||
$persian = ['۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹'];
|
||
$arabic = ['٠', '١', '٢', '٣', '٤', '٥', '٦', '٧', '٨', '٩'];
|
||
$latin = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
|
||
|
||
$result = str_replace($persian, $latin, $number);
|
||
$result = str_replace($arabic, $latin, $result);
|
||
|
||
return $result;
|
||
}
|
||
|
||
/**
|
||
* Format a number with grouping separator.
|
||
*/
|
||
public static function formatNumber(string|int|float $number, int $decimals = 0, string $locale = 'fa_IR'): string
|
||
{
|
||
if (class_exists(\NumberFormatter::class)) {
|
||
try {
|
||
$formatter = new \NumberFormatter($locale, \NumberFormatter::DECIMAL);
|
||
$formatter->setAttribute(\NumberFormatter::FRACTION_DIGITS, $decimals);
|
||
|
||
return $formatter->format((float) $number);
|
||
} catch (\Exception $e) {
|
||
// Fallback below
|
||
}
|
||
}
|
||
|
||
return number_format((float) $number, $decimals);
|
||
}
|
||
|
||
/**
|
||
* Format a number as currency.
|
||
*/
|
||
public static function formatCurrency(string|int|float $amount, string $currency = 'IRR', string $locale = 'fa_IR', int $decimals = 0): string
|
||
{
|
||
if (class_exists(\NumberFormatter::class)) {
|
||
try {
|
||
$formatter = new \NumberFormatter($locale, \NumberFormatter::CURRENCY);
|
||
$formatter->setAttribute(\NumberFormatter::FRACTION_DIGITS, $decimals);
|
||
|
||
return $formatter->formatCurrency((float) $amount, $currency);
|
||
} catch (\Exception $e) {
|
||
// Fallback below
|
||
}
|
||
}
|
||
|
||
return number_format((float) $amount, $decimals) . ' ' . $currency;
|
||
}
|
||
|
||
/**
|
||
* Format a number as a percentage.
|
||
*/
|
||
public static function formatPercentage(string|int|float $value, int $decimals = 1, string $locale = 'fa_IR'): string
|
||
{
|
||
if (class_exists(\NumberFormatter::class)) {
|
||
try {
|
||
$formatter = new \NumberFormatter($locale, \NumberFormatter::PERCENT);
|
||
$formatter->setAttribute(\NumberFormatter::FRACTION_DIGITS, $decimals);
|
||
|
||
return $formatter->format((float) $value / 100);
|
||
} catch (\Exception $e) {
|
||
// Fallback below
|
||
}
|
||
}
|
||
|
||
return number_format((float) $value, $decimals) . '%';
|
||
}
|
||
}
|