Created
February 2, 2021 14:29
-
-
Save gharabaghi/5cdcfbc2404f4ec20a62b0bb9884680e to your computer and use it in GitHub Desktop.
php format a currency numbered string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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