Last active
September 1, 2022 14:00
-
-
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
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 | |
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