Skip to content

Instantly share code, notes, and snippets.

@mayeenulislam
Last active September 5, 2021 06:02
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 mayeenulislam/9cbd7bc260ccd64575c942872b48b5bc to your computer and use it in GitHub Desktop.
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.
<?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 <wz.islam@gmail.com>
* @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