Last active
September 5, 2021 06:02
-
-
Save mayeenulislam/9cbd7bc260ccd64575c942872b48b5bc to your computer and use it in GitHub Desktop.
Truncate amount in Indian money format like Lakh, Koti (Lac, Crore), and in US money format like Million, Billion, Trillion etc.
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
<?php | |
/** | |
* Truncate Amount (in Indian format). | |
* | |
* Return amount in lac/koti etc. | |
* | |
* @param integer $amount Amount. | |
* | |
* @link https://stackoverflow.com/q/42571702/1743124 (Concept) | |
* | |
* @author Mayeenul Islam <[email protected]> | |
* @link https://gist.github.com/mayeenulislam/9cbd7bc260ccd64575c942872b48b5bc | |
* | |
* @return array Array of truncated amount and label. | |
*/ | |
function truncateAmountIndian($amount) | |
{ | |
// Known issue: strlen() on string returns wrong estimation. | |
$length = strlen((float) $amount); | |
if ($length <= 3) { | |
$amountOutput = (int) $amount; | |
$label = ''; | |
} elseif ($length === 4 || $length === 5) { | |
// 1,000 - 99,999. | |
$amountOutput = round(($amount / 1000), 2); | |
$label = 'k'; | |
} elseif ($length === 6 || $length === 7) { | |
// 1,00,000 - 99,99,999. | |
$amountOutput = round(($amount / 100000), 2); | |
$label = 'Lac'; | |
} elseif ($length > 7) { | |
// 1,00,00,000 - 99,99,99,999+. | |
$amountOutput = round(($amount / 10000000), 2); | |
$label = 'Cr.'; | |
} | |
return array( | |
'amount' => $amountOutput, | |
'label' => $label, | |
); | |
} | |
/** | |
* Truncate Amount (in US format). | |
* | |
* Return amount in million/billion/trillion etc. | |
* | |
* @param integer $amount Amount. | |
* | |
* Source: unknown | |
* | |
* @return array Array of truncated amount and label. | |
*/ | |
function truncateAmountUS($amount) | |
{ | |
// filter and format it | |
if ($amount < 1000) { | |
// 0 - 1000 | |
$amountOutput = (int) $amount; | |
$label = ''; | |
} elseif ($amount < 900000) { | |
// 0.9k-850k | |
$amountOutput = round(($amount / 1000), 2); | |
$label = 'k'; | |
} elseif ($amount < 900000000) { | |
// 0.9m-850m | |
$amountOutput = round(($amount / 1000000), 2); | |
$label = 'm'; | |
} elseif ($amount < 900000000000) { | |
// 0.9b-850b | |
$amountOutput = round(($amount / 1000000000), 2); | |
$label = 'b'; | |
} else { | |
// 0.9t+ | |
$amountOutput = round(($amount / 1000000000000), 2); | |
$label = 't'; | |
} | |
return array( | |
'amount' => $amountOutput, | |
'label' => $label, | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment