vernova/app/Helpers/NumberHelper.php
Kazem Alghasi b6b2057df2
Some checks failed
Tests / PHP ${{ matrix.php }} (8.2) (push) Has been cancelled
Tests / PHP ${{ matrix.php }} (8.3) (push) Has been cancelled
اولین کامیت پروژه vernova
2026-07-26 19:58:27 +03:30

90 lines
2.9 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?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) . '%';
}
}