尼斯PHP算法转换成1.2“120万”?尼斯、转换成、算法、PHP

2023-09-11 02:20:43 作者:来一碗小仙女

我一直在苦苦寻找一个很好的算法,以更改号码(可以是浮动或整数)到一个很好的格式化人类可读的数字显示的单位为字符串。例如:

I've been struggling to find a nice algorithm to change a number (could be a float or integer) into a nicely formated human readable number showing the units as a string. For example:

100500000 -> '100.5 Mil'
200400 -> '200.4 K'
143000000 -> '143 Mil'
52000000000 -> '52 Bil'

等等,你的想法。

etc, you get the idea.

任何指针?

推荐答案

我会适应下code(我发现在网络上):

I'd adapt the code below (which i found on the net):

code归功于这个环节,我发现: HTTP:/ /www.phpfront.com/php/human-readable-byte-format/

Code credit goes to this link i found: 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 )];
}

不要忘了改1024年至1000年,虽然...

Don't forget to change 1024 to 1000 though ...