Download the PHP package kschu91/largest-remainder-method without Composer
On this page you can find all versions of the php package kschu91/largest-remainder-method. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download kschu91/largest-remainder-method
More information about kschu91/largest-remainder-method
Files in kschu91/largest-remainder-method
Package largest-remainder-method
Short Description A PHP implementation of the largest remainder method algorithm. This method is the most common way to get rid of rounding issues when working with rounded percentage values.
License
Informations about the package largest-remainder-method
largest remainder method algorithm
A PHP implementation of the largest remainder method algorithm. This method is the most common way to get rid of rounding issues when working with rounded percentage values.
The problem
Assume the following example:
When rounding the above percentages using PHP´s rounding functions, we get:
Which in fact sums up to 101%
instead of 100%
. The largest remainder method solves this issue by doing the following steps:
- Rounding all values down to the nearest integer value
- Determining the difference between the sum of the rounded values and total value
- Distributing the difference between the rounded values in decreasing order of their decimal parts
Installation
If you are not familiar with composer: composer basic usage
Requirements
- PHP >= 7.3
Basic Usage
which results in:
Working with decimals aka. precision
The default precision is set to 0
. But you can change this behaviour by using the setPrecision
method:
which results in:
Working with complex arrays/objects
Mostly, you don´t have the numbers you want to apply this algorithm on in a simple array as in the examples above. You rather have them in objects or associative arrays. That´s why this library also supports callbacks for applying this algorithm.
You just have to supply 2 callbacks to the usort
method. The first one, to fetch the relevant number from the object. And the second one to write the rounded number back to the resulting object.
Make sure to pass the first argument of the setter callback as reference, eg. as in the example below:
&$item
. If not, the resulting data will maintain their original numbers and are not rounded.
which results in: