Skip to content

Instantly share code, notes, and snippets.

@minedun6
Created July 7, 2022 15:36
Show Gist options
  • Save minedun6/d11987af1662644f168460b3ee5032e0 to your computer and use it in GitHub Desktop.
Save minedun6/d11987af1662644f168460b3ee5032e0 to your computer and use it in GitHub Desktop.
Simplify sizes
<?php
function simplify(int | float $value) : string {
$regex = '/^-?\d+(?:\.\d{0,1})?/';
$format = function ($value) use ($regex) {
preg_match($regex, $value, $matches, PREG_OFFSET_CAPTURE);
return str_replace('.0', '', $matches[0][0]);
}
// Hundred (or less)
if ($value < 1000) {
return $value;
}
// Thounsads
if ($value < 1000000) {
return $format($value / 1000) . 'k';
}
// Millions
if ($value < 1000000000) {
return $format($value / 1000000) . 'M';
}
// Billions
return $format($value / 1000000000) . 'B';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment