在输入为“ 100K”,“ 100M”的情况下转换金额。等等 [英] Convert amounts where input is "100K", "100M" etc

查看:171
本文介绍了在输入为“ 100K”,“ 100M”的情况下转换金额。等等的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前在一个网站上工作,我需要转换后面带有字母的金额,例如:

I am currently working on a site where i need to convert amounts with letters behind it, example:

100M = 100.000.000

我创建了另一种方式来实现此目的,来自:

I have created a way to do this the other way, from:

100.000.000 = 100M

这是我当前的函数:

function Convert($Input){

if($Input<=1000){
    $AmountCode = "GP";
    $Amount = $Input;
}
else if($Input>=1000000){
    $AmountCode = "M";
    $Amount = floatval($Input / 1000000);
}
else if($Input>=1000){
    $AmountCode = "K";
    $Amount = $Input / 1000;

}

$Array = array(
    'Amount' => $Amount,
    'Code' => $AmountCode
);

$Result = json_encode($Array);

return json_decode($Result);

}

现在我需要一些可以过滤掉的东西:

Now i need something that can filter out this:

100GP = 100
100K  = 100.000
100M  = 100.000.000

我一直在寻找一些东西,并且我尝试使用 explode(); 和其他功能,但它不能像我想要的那样工作。.

Ive been looking around for some things and ive tried with explode(); and other functions but it doesnt work like i want it to..

有没有人可以帮助我?

推荐答案

<?php
/**
  * @param string $input
  * @return integer
  */
function revert($input) {
    if (!is_string($input) || strlen(trim($input)) == 0) {
        throw new InvalidArgumentException('parameter input must be a string');
    }
    $amountCode = array ('GP'   => '',
                         'K'    => '000',
                         'M'    => '000000');
    $keys       = implode('|', array_keys($amountCode));
    $pattern    = '#[0-9]+(' . $keys .'){1,1}$#';
    $matches    = array();

    if (preg_match($pattern, $input, $matches)) {
        return $matches[1];
    }
    else {
        throw new Exception('can not revert this input: ' . $input);
    }
} 

这篇关于在输入为“ 100K”,“ 100M”的情况下转换金额。等等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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