Convert amounts where input is “100K”, “100M” etc

人盡茶涼 提交于 2019-12-07 19:21:15

问题


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

Here is my current function:

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

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

Is there anyone who can help me out ?


回答1:


<?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);
    }
} 


来源:https://stackoverflow.com/questions/32623315/convert-amounts-where-input-is-100k-100m-etc

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!