PHP Count round thousand to a K style count like facebook Share . . . Twitter Button ect

后端 未结 12 1873
北恋
北恋 2020-12-13 05:15

Ok so I am trying to turn my hit counter to round thousands to a single digit too display 3 thousand hits as 3K for example, like the Facebook Share and Twitter Tweet Button

12条回答
  •  佛祖请我去吃肉
    2020-12-13 05:59

    This questuion have the same goal as this question in here Shorten long numbers to K/M/B?

    Reference: https://gist.github.com/RadGH/84edff0cc81e6326029c

    Try this code:

    function number_format_short( $n, $precision = 1 ) {
        if ($n < 900) {
            // 0 - 900
            $n_format = number_format($n, $precision);
            $suffix = '';
        } else if ($n < 900000) {
            // 0.9k-850k
            $n_format = number_format($n / 1000, $precision);
            $suffix = 'K';
        } else if ($n < 900000000) {
            // 0.9m-850m
            $n_format = number_format($n / 1000000, $precision);
            $suffix = 'M';
        } else if ($n < 900000000000) {
            // 0.9b-850b
            $n_format = number_format($n / 1000000000, $precision);
            $suffix = 'B';
        } else {
            // 0.9t+
            $n_format = number_format($n / 1000000000000, $precision);
            $suffix = 'T';
        }
      // Remove unecessary zeroes after decimal. "1.0" -> "1"; "1.00" -> "1"
      // Intentionally does not affect partials, eg "1.50" -> "1.50"
        if ( $precision > 0 ) {
            $dotzero = '.' . str_repeat( '0', $precision );
            $n_format = str_replace( $dotzero, '', $n_format );
        }
        return $n_format . $suffix;
    }
    

    The code above create a function to convert the numbers. To use this function later just call it like in the code below:

    // Example Usage:
    number_format_short(7201); // Output: 7.2k
    

提交回复
热议问题