-2

I have a variable that adds and returns numbers actually this numbers increases with time.

Now I want that if the numbers get to say 2000000 (2 millions) it should remove all the zeros and return 2m.

Any ideas how I can go about this ?

Obsidian
  • 3,719
  • 8
  • 17
  • 30
  • 1
    What when it gets to 2000001 - how should that be displayed. Have you tried any code yourself so far? – Nigel Ren Jul 14 '19 at 14:48

2 Answers2

0

you can use the following function

    function millionType($value){
        return ($value / 1000000)."m";
    }

    echo millionType(1500000); // 1.5m
    echo "<br/>";
    echo millionType(2000000); // 2m
    echo "<br/>";
    echo millionType(2500000); // 2.5m
    echo "<br/>";
    echo millionType(3000000); // 3m

Edit: you can use this, you can change it to your desire type.

function millionType($value){
        $million = (int)($value / 1000000);
        $surplus = ($value % 1000000);

        $myType = "";

        if($million > 0)
            $myType .= $million."m ";

        $thousands = (int)($surplus / 1000);
        if($thousands > 0)
            $myType .= $thousands."k ";

        $lastPart = ($surplus % 1000);
        if($lastPart > 0)
            $myType .=  "and ".$lastPart;

        echo $myType;
    }

    echo millionType(1500001); // 1m 500k and 1
    echo "<br />";
    echo millionType(1000001); // 1m and 1
    echo "<br />";
    echo millionType(10000540); // 10m and 540
Cotur
  • 450
  • 2
  • 10
0

Question is a duplicate of Shorten long numbers to K/M/B?

Neverthless here is my answer:

function shorten($number){
  $suffix = ["", "K", "M", "B"];
  $percision = 1;
  for($i = 0; $i < count($suffix); $i++){
    $divide = $number / pow(1000, $i);
    if($divide < 1000){
      return round($divide, $percision).$suffix[$i];
      break;
    }
  }
}
echo shorten(1000);
DreiDe
  • 109
  • 1
  • 10