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

2019-05-27 03:32发布

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 ?

标签: php currency
1条回答
Animai°情兽
2楼-- · 2019-05-27 03:56
<?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);
    }
} 
查看更多
登录 后发表回答