Skip to content

Instantly share code, notes, and snippets.

@jkoop
Forked from liunian/gist:9338301
Last active August 12, 2021 21:35
Show Gist options
  • Save jkoop/2e628e9099765070f1feeabd5183d724 to your computer and use it in GitHub Desktop.
Save jkoop/2e628e9099765070f1feeabd5183d724 to your computer and use it in GitHub Desktop.
php8.0 - number to metric with prefix for things like human readable file size
<?php
function numberToMetric(int|float $number, int $significantDigits = 3, bool $binary = false): string {
static $prefixes = ['y','z','a','f','p','n','μ','m','','k','M','G','T','P','E','Z','Y'];
$factor = floor((strlen(abs($number)) - 1) / 3) * (abs($number) <=> 1);
$metricBase = $binary ? 1024 : 1000;
$number = $number / pow($metricBase, $factor);
return sprintf("%.{$significantDigits}H", $number) . $prefixes[$factor+8];
}
// numberToMetric(12345) => '12.3k'
// numberToMetric(0.12345) => '123m'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment