我一直在努力寻找一种很好的算法来将数字(可以是浮点数或整数)更改为格式良好的人类可读数字,将单位显示为字符串。例如:
100500000 -> '100.5 Mil'
200400 -> '200.4 K'
143000000 -> '143 Mil'
52000000000 -> '52 Bil'
等等,你明白了。
任何指针?
我一直在努力寻找一种很好的算法来将数字(可以是浮点数或整数)更改为格式良好的人类可读数字,将单位显示为字符串。例如:
100500000 -> '100.5 Mil'
200400 -> '200.4 K'
143000000 -> '143 Mil'
52000000000 -> '52 Bil'
等等,你明白了。
任何指针?
我会修改下面的代码(我在网上找到的):
代码归功于我发现的这个链接: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 ...
<?php
function prettyNumber($number) // $number is int / float
{
$orders = Array("", " K", " Mil", " Bil");
$order=0;
while (($number/1000.0) >= 1.5) { // while the next step up would generate a number greater than 1.5
$order++;
$number/=1000.0;
}
if ($order)
return preg_replace("/\.?0+$/", "",
substr(number_format($number, 2),0,5)).$orders[$order];
return $number;
}
$tests = array(100500000,200400,143000000,52000000000);
foreach ($tests as $test)
{
echo $test." -> '".prettyNumber($test)."'\n";
}
log()
如果您仍然感兴趣,这里是一个版本:
function wordify($val, $decimalPlaces = 1) {
if ($val < 1000 && $val > -1000)
return $val;
$a = array( 0 => "", 1 => "K", 2 => "Mil", 3 => "Bil", 4 => "Tril", 5 => "Quad" );
$log1000 = log(abs($val), 1000);
$suffix = $a[$log1000];
return number_format($val / pow(1000, floor($log1000)), $decimalPlaces, '.', '') . " $suffix";
}
$tests = array(-1001, -970, 0, 1, 929, 1637, 17000, 123456, 1000000, 1000000000, 1234567890123);
foreach ($tests as $num) {
echo wordify($num)."<br>";
}