-3

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

我在想一些事情:

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

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

4

2 回答 2

5

您可以创建自己的函数,因为没有内置函数。给你一个想法:

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

于 2013-01-16T14:15:35.150 回答
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);
    }
?>
于 2013-01-16T14:11:04.563 回答