Calculator

By sunslayer on Nov 21, 2009

besides the basic calc functions (+-/) this can also do abbreviations for numbers ex: calc("1m+3k-2") will return "1002998" calc("1.1m+1m") will return "2100000" calc("1.52") will return "3"

this will also calculate powers (^) and modulos (%)

<?php
  function calc($a) {
    $functions="/(\+|\-|\*|\/|\^|\%)/";
    $num=explode(chr(124),preg_replace($functions,"|",$a));
    $a=str_split($a);$d=0;
    foreach ($a as $b => $c) {
      if (preg_match($functions,$c)) {
        $sign[$d]=$c;$d++;
      }
    }$d=0;
    while ($d<=count($num)) {
      $num1=iif($num3,$num3,rep($num[$d]));
      $num2=rep($num[$d+1]);
      $sign1=$sign[iif($num3,$d,0)];
      $d++;
      if (preg_match("/./",$sign1)) {
        switch ($sign1) {
          case "+":
            $num3=$num1+$num2;
            break;
          case "-":
            $num3=$num1-$num2;
            break;
          case "*":
            $num3=$num1*$num2;
            break;
          case "/":
            $num3=$num1/$num2;
            break;
          case "^":
            $x=$num2;$num3=1;
            while ($x) {
              $num3*=$num1;$x--;
            }
            break;
          case "%":
            $num3=$num1%$num2;
            break;
        }
      }else return $num3;
    }return $num3;
  }
  function iif($if,$T,$F) {
    if ($if) return $T;
    else return $F;
  }
  function rep($num) {
    if (preg_match("/.*\.(.*)/",$num,$len)&&preg_match("/[a-z]/i",$num)) {
      $len=strlen(preg_replace("/\D/","",$len[1])).chr(10);
      $k=str_repeat(0,3-$len);$m=str_repeat(0,6-$len);$b=str_repeat(0,9-$len);
      $num=str_replace("k",$k,str_replace("m",$m,str_replace("b",$b,str_replace(".","",$num))));
    }elseif (preg_match("/.*\.(.*)/",$num,$len)&&!preg_match("/[a-z]/i",$num))
      $num=$num;
    else
      $num=str_replace("k","000",str_replace("m","000000",str_replace("b","000000000",$num)));
    return $num;
  }
?>

Comments

Sign in to comment.
sunslayer   -  Nov 23, 2009

ye it is pretty if u use it for that purpose but the main reason i made this was for calculating like "1m+2.4m" etc.

More
 Respond  
^Neptune   -  Nov 23, 2009

Good snippet, nice use of case statements.

However it is a tad useless since you can just do

variable = variable + 1
variable += 1
variable++

and such.

I would rather just use built in functionalities than having to include a function in every PHP script. Still, nice example though.

More
 Respond  
sunslayer   -  Nov 21, 2009

lies> Calculator

PHP Code

More
 Respond  
Ghost-writer   -  Nov 21, 2009

nubcake is this mirc or php?

Calculator mIRC Code

Make up your mind.

More
 Respond  
Are you sure you want to unfollow this person?
Are you sure you want to delete this?
Click "Unsubscribe" to stop receiving notices pertaining to this post.
Click "Subscribe" to resume notices pertaining to this post.