数字格式< -

时间:2014-12-19 07:48:39

标签: php numbers format

所以我有一个像Youtube这样的网站视频,问题是那个

我想要这样的数字例如:

1,234次观看 - > 1,2 K

所以这是代码

function pm_number_format($number, $decimals = 0, $dec_point = '.', $thousands_sep = ',')
{
    return number_format($number, $decimals, $dec_point, $thousands_sep);
}
function pm_compact_number_format($number)
{
    if ($number < 10000)
    {
        return pm_number_format($number);
    }
    $d = $number < 1000000 ? 1000 : 1000000;
    $f = round($number / $d, 1);

    return pm_number_format($f, $f - intval($f) ? 1 : 0) . ($d == 1000 ? 'k' : 'M');
}

1 个答案:

答案 0 :(得分:0)

只需更改你的if条件并删除1x零,所以从这个:

if ($number < 10000) {
    return pm_number_format($number);
}

到此:

if ($number < 1000) {
    return pm_number_format($number);
}

输入:

1
12
123
1234
12345
123456
1234567
12345678
123456789

输出:

1
12
123
1.2K  //<--See output as you wanted
12.3K
123.5K
1.2M
12.3M
123.5M

修改

这是我修改的代码(如上所述)并用于生成输出:

<?php

    function pm_number_format($number, $decimals = 0, $dec_point = '.', $thousands_sep = ',') {
        return number_format($number, $decimals, $dec_point, $thousands_sep);
    }

    function pm_compact_number_format($number) {
        if ($number < 1000)
            return pm_number_format($number);

        $d = $number < 1000000 ? 1000 : 1000000;
        $f = round($number / $d, 1);

        return pm_number_format($f, $f - intval($f) ? 1 : 0) . ($d == 1000 ? 'k' : 'M');
    }


    $number = "";

    foreach(range(1,10) as $value) {
        $number .= $value;
        echo pm_compact_number_format($number) . "<br />";
    }

?>