php 数字如 (10M, ..) [英] php numbers like (10M, ..)

查看:32
本文介绍了php 数字如 (10M, ..)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想处理像 10M(代表 10 000 000)和 100K 等数字.PHP 中是否已经存在一个函数,或者做我必须编写自己的函数吗?

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?

我在想:

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

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

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

推荐答案

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

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

演示: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

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

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 :)

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

这篇关于php 数字如 (10M, ..)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆