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

后端 未结 12 1838
北恋
北恋 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:58

    Rounding up, not accounting for any abbreviations above 'k' or thousands, showing one decimal place.

    function numToKs($number) {
        if ($number >= 1000) {
            return number_format(($number / 1000), 1) . 'k';
        } else {
            return $number;
        }
    }
    
    numToKs(1)          = 1
    numToKs(111)        = 111
    numToKs(999)        = 999
    numToKs(1000)       = "1.0k"
    numToKs(1499)       = "1.5k"
    numToKs(1500)       = "1.5k"
    numToKs(1501)       = "1.5k"
    numToKs(1550)       = "1.6k"
    numToKs(11501)      = "11.5k"
    numToKs(1000000000) = "1,000,000.0k"
    numToKs(1234567890) = "1,234,567.9k"
    

提交回复
热议问题