-3

I have numbers that are given to me in the following format:

12.2K

I would instead like to convert this number to display:

12200

The examples ive seen convert to K format, but I would like to convert from K format.

Is there an easy way to do this?

Thanks!

deverguy
  • 1
  • 1
  • 3

4 Answers4

0

You mean, something like this? This will be able to convert thousands and millions, etc.

<?php
  $s = "12.2K";
  if (strpos(strtoupper($s), "K") != false) {
    $s = rtrim($s, "kK");
    echo floatval($s) * 1000;
  } else if (strpos(strtoupper($s), "M") != false) {
    $s = rtrim($s, "mM");
    echo floatval($s) * 1000000;
  } else {
    echo floatval($s);
  }
?>
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
0
$result = str_ireplace(['.', 'K'], ['', '00'], '12.2K');

You can also expand this by other letters etc.

0
<?php
$number = '12.2K';

if (strpos($number, 'K') !== false)
    {
    $number = rtrim($number, 'K') * 1000;
    }

echo $number
?>

Basically, you just want to check if the string contains a certain character, and if it does, respond to it by taking it out and multiplying it by 1000.

0

An alternative method is to have the abbreviations in an array and use power of to calculate the number to multiply with.
This gives a shorter code if you have lots of abbreviations.
I use strtoupper to make sure it matches both k and K.

$arr = ["K" => 1 ,"M" => 2, "T" => 3]; // and so on for how ever long you need

$input = "12.2K";
if(isset($arr[strtoupper(substr($input, -1))])){ //does the last character exist in array as an key
    echo substr($input,0,-1) * pow(1000, $arr[strtoupper(substr($input, -1))]); //multiply with the power of the value in array
    //      12.2             *       1000^1
}else{
    echo $input; // less than 1k, just output
}

https://3v4l.org/LXVXN

Andreas
  • 23,610
  • 6
  • 30
  • 62