Member-only story

šŸ”µ 4 New Rounding Methods Likely In PHP 8.4

Tom Smykowski
2 min readNov 27, 2023

--

PHP 8.4 may come with four new methods of rounding numbers for fine-tuned statistical analysis of data

You could say rounding is my pony. Actually after writing the article about it in January i almost forgot about the issue.

The issue being that thereā€™s no onr standard way of rounding. Actually thereā€™s a lot of rounding methods.

Specifically when your value is exactly between two integers, like 8.5, it can be rounded based on several rules that are different in various languages. Some round up (ceiling), down (floor), away from zero, toward zero, to closest even or to closest odd number.

Itā€™s important how you round numbers because it impacts operations on numbers.

For example if you round 1.5 and 2.5 to ceiling you get 2 and 3. An average of the sum of these numbers is 5 / 2 = 2.5.

However, the exact average is 4/2 = 2.

On the other hand when you round to even, you get 2 and 2. Average is 2.

As you can see the value is closer to the real value than rounding to ceiling.

It means that itā€™s important how you round your data.

So Iā€™ve almost forgot about that topic until Iā€™ve found the RFC for PHP 8.4

The proposal of Jorg Sowa four ways to cut the tie of rounding:

  • PHP_ROUND_CEILING - rounds num to the nearest integer bigger than num,
  • PHP_ROUND_FLOOR - rounds num to the nearest integer lower than num,
  • PHP_ROUND_AWAY_FROM_ZERO - rounds num away from zero,
  • PHP_ROUND_TOWARD_ZERO - rounds num towards zero.

It will supplement already available methods of rounding:

  • PHP_ROUND_HALF_UP Rounds num away from zero when it is half way there, making 1.5 into 2 and -1.5 into -2.
  • PHP_ROUND_HALF_DOWN Rounds num towards zero when it is half way there, making 1.5 into 1 and -1.5 into -1.
  • PHP_ROUND_HALF_EVEN Rounds num towards the nearest even value when it is half way there, making both 1.5 and 2.5 into 2.
  • PHP_ROUND_HALF_ODD Rounds num towards the nearest odd value when it is half way there, making 1.5 into 1 and 2.5 into 3.

Itā€™s expected that the new rounding methods will be available in PHP 8.4. The voting on the change was pretty uniform with some mixed results of technical organisation that should not impact the solution as it is.

That way weā€™ll have 9 rounding methods satisfying the tastes of the most demanding rounders like the author of this text.

Whatā€™s your favorite rounding method? Mine is rounding to odd, itā€™s fancy šŸ™‚

If you like Expanse TV series subscribe to my articles ā˜ŗļø Or coding šŸ™‚

source, source 2

--

--

Tom Smykowski
Tom Smykowski

Written by Tom Smykowski

Hi! My name is Tom Smykowski, and Iā€™m a Staff Frontend Engineer. Grab a free scalable Angular app checklist: https://tomasz-smykowski.com/scalable-angular

No responses yet

Write a response