很好的PHP算法将120000000转换为'120 mil'?

Gar*_*hby 1 php algorithm formatting numbers

我一直在努力找到一个很好的算法来将一个数字(可能是一个浮点数或整数)改成一个很好的格式化的人类可读数字,将单位显示为一个字符串.例如:

100500000 -> '100.5 Mil'
200400 -> '200.4 K'
143000000 -> '143 Mil'
52000000000 -> '52 Bil'
Run Code Online (Sandbox Code Playgroud)

等等,你明白了.

有什么指针吗?

Chr*_*heD 6

我会调整下面的代码(我在网上找到):

我发现代码信用到这个链接:http://www.phpfront.com/php/human-readable-byte-format/

function humanReadableOctets($octets)
{
    $units = array('B', 'kB', 'MB', 'GB', 'TB'); // ...etc

    for ($i = 0, $size =$octets; $size>1024; $size=$size/1024)
        $i++;

    return number_format($size, 2) . ' ' . $units[min($i, count($units) -1 )];
} 
Run Code Online (Sandbox Code Playgroud)

不要忘记将1024更改为1000但...

  • 你实际上可以单独做一些$ unit = $ units [log($ n)]的行 (6认同)