Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
601 views
in Technique[技术] by (71.8m points)

php numbers like (10M, ..)

I would like to work with numbers like 10M (which represents 10 000 000), and 100K etc. Is there a function that already exists in PHP, or do I have to write my own function?

I'm thinking something along the lines of :

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

Also, taking it one step further and doing the opposite, something to translate and get 100K from 100000?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could whip up your own function, because there isn't an builtin function for this. To give you an idea:

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];
}

Demo: http://codepad.viper-7.com/2rxbP8

Or the other way around:

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

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

Demo: http://codepad.viper-7.com/VeRGDs


If you want to get really funky you could put all that in a class and let it decide what conversion to run:

<?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

Although this may be a bit overkill :)

Demo: http://codepad.viper-7.com/KZEc7b


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...