albertoarena / calculator
Simple calculator
v1.0.1
2024-12-16 09:41 UTC
Requires
- php: ^8.2
Requires (Dev)
- jaschilz/php-coverage-badger: ^2.0
- larastan/larastan: ^3.0
- laravel/pint: dev-main
- phpstan/phpstan: ^2.0
- phpunit/phpunit: 11.5.x-dev
This package is not auto-updated.
Last update: 2024-12-19 01:48:51 UTC
README
Simple PHP calculator, inspired by shunting-yard algorithm.
It supports basic operators (+, -, /, *, ^), trigonometric operators and precedence.
Compatibility
Operators
Operator precedence follows the standard (see Wikipedia):
How to use it
A working example is available in samples/basic.php
.
use Calculator\Calculator; $calculator = new Calculator(); // ---------------------------- // Basic operators // ---------------------------- $calculator->number(1) ->operator('+')->number(5) ->operator('*')->number(3.5) ->operator('/')->number(2) ->execute(); echo $calculator; // ==> 1 + 5 * 3.5 / 2 = 9.75 // ---------------------------- // Power // ---------------------------- $calculator->number(2) ->operator('*')->number(2) ->operator('^')->number(4) ->execute(); echo $calculator; // ==> 2 * 2 ^ 4 = 32 // ---------------------------- // Square root // ---------------------------- $result = $calculator->number(9) ->operator('√') ->execute(); echo $calculator; // ==> √9 = 3 // ---------------------------- // Trigonometry // ---------------------------- $result = $calculator->number(1) ->operator('cos') ->execute(); echo $calculator; // ==> cos(1) = 0.54030230586814 // ---------------------------- // Fibonacci number // ---------------------------- $result = $calculator->number(40) ->operator('!') ->execute(); echo $calculator; // ==> 40! = 102334155 // ---------------------------- // Percentage // ---------------------------- $result = $calculator->number(40.32) ->operator('%') ->execute(); echo $calculator; // ==> 40.32% = 0.4032 // ---------------------------- // Group operations (parentheses) // ---------------------------- $result = $calculator ->group(function (Calculator $calculator) { $calculator ->number('pi') ->operator('/')->number(4); }) ->operator('cos') ->execute(); echo $calculator; // ==> cos(pi / 4) = 0.7071067811865