Update besar apk finance
This commit is contained in:
@@ -0,0 +1,6 @@
|
||||
<?php
|
||||
defined('BASEPATH') OR exit('No direct script access allowed');
|
||||
class FormulaService
|
||||
{
|
||||
public function calculate($expression,array$vars){$expression=trim((string)$expression);if($expression==='')return 0;preg_match_all('/[A-Za-z_][A-Za-z0-9_]*|\d+(?:\.\d+)?|[()+\-*\/]/',$expression,$m);$tokens=$m[0];if(preg_replace('/\s+/','',$expression)!==implode('',$tokens))throw new BusinessException('Formula mengandung token yang tidak diizinkan.');$out=array();$ops=array();$prec=array('+'=>1,'-'=>1,'*'=>2,'/'=>2);foreach($tokens as$t){if(is_numeric($t)||preg_match('/^[A-Za-z_]/',$t))$out[]=$t;elseif($t==='(')$ops[]=$t;elseif($t===')'){while($ops&&end($ops)!=='(')$out[]=array_pop($ops);if(!$ops)throw new BusinessException('Kurung formula tidak seimbang.');array_pop($ops);}else{while($ops&&end($ops)!=='('&&$prec[end($ops)]>=$prec[$t])$out[]=array_pop($ops);$ops[]=$t;}}while($ops){$x=array_pop($ops);if($x==='(')throw new BusinessException('Kurung formula tidak seimbang.');$out[]=$x;}$stack=array();foreach($out as$t){if(isset($prec[$t])){$b=array_pop($stack);$a=array_pop($stack);if($t==='/'&&abs($b)<.0000001)throw new BusinessException('Pembagian nol pada formula.');$stack[]=$t==='+'?$a+$b:($t==='-'?$a-$b:($t==='*'?$a*$b:$a/$b));}else$stack[]=is_numeric($t)?(float)$t:(isset($vars[$t])?(float)$vars[$t]:0);}if(count($stack)!==1)throw new BusinessException('Formula tidak valid.');return round($stack[0],2);}
|
||||
}
|
||||
Reference in New Issue
Block a user