Thousand Separator

Author: Iqbal Hossain

Some time we need to show the number specially currency to thousand separator. We can use number_format function in PHP. But it does not give desire result in case of south asian region. In India, Bangladesh and other countries of this region use different format. Let's see the example and solution. Western format: 10,000,000,000.00   <- Every 3 digits from right to left Bangladesh/India format: 10,00,00,00,000.00  <- First 3 digits from right and then 2 digits interval We can use two different way to solve this problem. Solution-1:
$num = '10000000000000000000';
//Format of Bangladesh/India
setlocale(LC_MONETARY, 'en_IN');
$numIn = money_format('%!.0i', $num);
echo "BD/In: " . $numIn;

//Output: In: 1,00,00,00,00,00,00,00,00,000

//Format of Japan, USA
setlocale(LC_MONETARY, 'en_US');
$numJp = money_format('%!.0i', $num);
echo "Jp/USA: " . $numJp;

//Output: Jp: 10,000,000,000,000,000,000
Solution-2: Using additional function. It works for both Integer and Float value.
function formatToIndia($amount): string
{
list ($number, $decimal) = explode('.', sprintf('%.2f', floatval($amount)));
$sign = $number < 0 ? '-' : '';
$number = abs($number);
for ($i = 3; $i < strlen($number); $i += 3)
{
$number = substr_replace($number, ',', -$i, 0);
}
return $sign . $number . '.' . $decimal;
}
Solution-1 has limitation. It does not work in windows environment. On the other hand Solution-2 is flexible and can change according to requirement.