Skip to content

Instantly share code, notes, and snippets.

@bdeleasa
Last active September 1, 2022 14:00
Show Gist options
  • Save bdeleasa/f1f053bab5d7a78ab9038c3432e6ad6a to your computer and use it in GitHub Desktop.
Save bdeleasa/f1f053bab5d7a78ab9038c3432e6ad6a to your computer and use it in GitHub Desktop.
PHP function to convert a given number to a shorthand version. Ex: convert $1,000,000 to $1M
<?php
if ( ! function_exists( 'PREFIX_abbreviate_num' ) ) {
/**
* Converts the given number to an abbreviated version of it and returns that value.
*
* Ex: PREFIX_abbreviate_num( 100000 ) would output 100K.
*
* @since 1.0.0
*
* @param $num int
* @return string
*/
function PREFIX_abbreviate_num( $num ) {
$units = ['', 'K', 'M', 'B', 'T'];
for ($i = 0; $num >= 1000; $i++) {
$num /= 1000;
}
return round($num, 1) . $units[$i];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment