How to format numbers similar to Stack Overflow reputation format

前端 未结 8 1023
我在风中等你
我在风中等你 2020-11-27 06:41

I want to convert a number into a string representation with a format similar to Stack Overflow reputation display.

e.g.

  • 999 == \'999\'
  • 1000 =
8条回答
  •  日久生厌
    2020-11-27 07:19

    // Shortens a number and attaches K, M, B, etc. accordingly
    function number_shorten($number, $precision = 3, $divisors = null) {
    
        // Setup default $divisors if not provided
        if (!isset($divisors)) {
            $divisors = array(
                pow(1000, 0) => '', // 1000^0 == 1
                pow(1000, 1) => 'K', // Thousand
                pow(1000, 2) => 'M', // Million
                pow(1000, 3) => 'B', // Billion
                pow(1000, 4) => 'T', // Trillion
                pow(1000, 5) => 'Qa', // Quadrillion
                pow(1000, 6) => 'Qi', // Quintillion
            );    
        }
    
        // Loop through each $divisor and find the
        // lowest amount that matches
        foreach ($divisors as $divisor => $shorthand) {
            if (abs($number) < ($divisor * 1000)) {
                // We found a match!
                break;
            }
        }
    
        // We found our match, or there were no matches.
        // Either way, use the last defined value for $divisor.
        return number_format($number / $divisor, $precision) . $shorthand;
    }
    

    This worked for me. I hope, this will help you. Thanks for asking this question.

提交回复
热议问题