-
-
Save relliv/f214874ced1e5626309d34f937553950 to your computer and use it in GitHub Desktop.
Easily readable numbers with custom locale
This file contains hidden or 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 | |
namespace App\Helpers; | |
/** | |
* Numbers more readable for humans | |
* It intends to change numbers as 1000 as 1K or 1200000 as 1.2M | |
* This code is heavly base in this one: https://gist.github.com/RadGH/84edff0cc81e6326029c | |
* How to use \NumberFormat::readable(1000); | |
* | |
* Source: https://gist.github.com/maurobaptista/1c7ec5e71bac9bd20137cd01d390bdaa | |
*/ | |
class ReadableNumberHelper | |
{ | |
/** @var array ['suffix' => 'threshold'] */ | |
private static $thresholds = [ | |
'' => 900, | |
'K' => 900000, | |
'M' => 900000000, | |
'B' => 900000000000, | |
'T' => 90000000000000, | |
]; | |
/** @var string */ | |
private const DEFAULT = '0'; | |
/** | |
* Set custom locale | |
*/ | |
public static function locale($lang = 'en') | |
{ | |
if ($lang == 'tr'){ | |
self::$thresholds = [ | |
'' => 900, | |
'B' => 900000, | |
'Ml' => 900000000, | |
'Mr' => 900000000000, | |
'Tr' => 90000000000000, | |
]; | |
} | |
return self::class; | |
} | |
/** | |
* @param float $value | |
* @param int $precision | |
* @return string | |
*/ | |
public static function readable(float $value, int $precision = 1): string | |
{ | |
foreach (self::$thresholds as $suffix => $threshold) { | |
if ($value < $threshold) { | |
return self::format($value, $precision, $threshold, $suffix); | |
} | |
} | |
return self::DEFAULT; | |
} | |
/** | |
* @param float $value | |
* @param int $precision | |
* @param int $threshold | |
* @param string $suffix | |
* @return string | |
*/ | |
public static function format(float $value, int $precision, int $threshold, string $suffix): string | |
{ | |
$formattedNumber = number_format($value / ($threshold / self::$thresholds['']), $precision); | |
$cleanedNumber = (strpos($formattedNumber, '.') === false) | |
? $formattedNumber | |
: rtrim(rtrim($formattedNumber, '0'), '.'); | |
return "{$cleanedNumber} {$suffix}"; | |
} | |
} |
This file contains hidden or 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
# Example | |
<pre> | |
<!-- View Counts --> | |
<div class="grid my-3"> | |
<span class="inline-block font-bold text-xs"> | |
{{\App\Helpers\ReadableNumbersHelper::locale(Config::get('app.locale'))::readable(342345435)}} Views | |
</span> | |
</div> | |
</pre> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment