Skip to content

Instantly share code, notes, and snippets.

@gharabaghi
Created February 2, 2021 14:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gharabaghi/5cdcfbc2404f4ec20a62b0bb9884680e to your computer and use it in GitHub Desktop.
Save gharabaghi/5cdcfbc2404f4ec20a62b0bb9884680e to your computer and use it in GitHub Desktop.
php format a currency numbered string
public static function formatCurrencyString($currency)
{
$currencySubStr1 = $currency;
$currencySubStr2 = '';
$dotPos = strpos($currency, '.');
if ($dotPos) {
$currencySubStr1 = substr($currency, 0, $dotPos);
$currencySubStr2 = substr($currency, $dotPos + 1, strlen($currency) - 1);
}
$length = strlen($currencySubStr1);
$j = 0;
for ($i = $length - 1; $i >= 0; $i--) {
if (($length - $i) % 3 == 0 && $i != 0) {
$currencySubStr1 = substr($currencySubStr1, 0, $i) . ',' . substr($currencySubStr1, $i, $length - 1 + $j);
$j++;
}
}
if ($dotPos) {
$length = strlen($currencySubStr2);
$j = 0;
for ($i = $length - 1; $i >= 0; $i--) {
if (($i) % 3 == 0 && $i != 0) {
$currencySubStr2 = substr($currencySubStr2, 0, $i) . ',' . substr($currencySubStr2, $i, $length - 1 + $j);
$j++;
}
}
$currencySubStr2 = '.' . $currencySubStr2;
}
return $currencySubStr1 . $currencySubStr2;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment