php数字像(10M,..)

时间:2013-01-16 14:08:52

标签: php number-formatting

我想使用 10M (代表10 000 000)和 100K 等数字。是否有PHP中已存在的函数,或者我必须写自己的功能?

我正在考虑以下几点:

echo strtonum("100K"); // prints 100000

另外,更进一步,做相反的事情,翻译并从100000获得100K?

2 个答案:

答案 0 :(得分:4)

你可以掀起自己的功能,因为没有内置功能。给你一个想法:

function strtonum($string)
{
    $units = [
        'M' => '1000000',
        'K' => '1000',
    ];

    $unit = substr($string, -1);

    if (!array_key_exists($unit, $units)) {
        return 'ERROR!';
    }

    return (int) $string * $units[$unit];
}

演示:http://codepad.viper-7.com/2rxbP8

或者相反:

function numtostring($num)
{
    $units = [
        'M' => '1000000',
        'K' => '1000',
    ];

    foreach ($units as $unit => $value) {
        if (is_int($num / $value)) {
            return $num / $value . $unit;
        }
    }   
}

演示:http://codepad.viper-7.com/VeRGDs


如果你想变得非常时髦,你可以将所有这些放在一个类中,让它决定运行什么转换:

<?php

class numberMagic
{
    private $units = [];

    public function __construct(array $units)
    {
        $this->units = $units;
    }

    public function parse($original)
    {
        if (is_numeric(substr($original, -1))) {
            return $this->numToString($original);
        } else {
            return $this->strToNum($original);
        }
    }

    private function strToNum($string)
    {
        $unit = substr($string, -1);

        if (!array_key_exists($unit, $this->units)) {
            return 'ERROR!';
        }

        return (int) $string * $this->units[$unit];
    }

    private function numToString($num)
    {
        foreach ($this->units as $unit => $value) {
            if (is_int($num / $value)) {
                return $num / $value . $unit;
            }
        }   
    }
}

$units = [
    'M' => 1000000,
    'K' => 1000,
];
$numberMagic = new NumberMagic($units);
echo $numberMagic->parse('100K'); // 100000
echo $numberMagic->parse(100); // 100K

虽然这可能有点矫枉过正:)

演示:http://codepad.viper-7.com/KZEc7b

答案 1 :(得分:2)

第二个

<?php
    #    Output easy-to-read numbers
    #    by james at bandit.co.nz
    function bd_nice_number($n) {
        // first strip any formatting;
        $n = (0+str_replace(",","",$n));

        // is this a number?
        if(!is_numeric($n)) return false;

        // now filter it;
        if($n>1000000000000) return round(($n/1000000000000),1).' trillion';
        else if($n>1000000000) return round(($n/1000000000),1).' billion';
        else if($n>1000000) return round(($n/1000000),1).' million';
        else if($n>1000) return round(($n/1000),1).' thousand';

        return number_format($n);
    }
?>