Req #79073 [Com]: round() does not have PHP_ROUND_UP or PHP_ROUND_DOWN modes
| From: | objecttothis at gmail dot com | Date: | Tue, 07 Jan 2020 12:00:32 +0000 |
| Subject: | Req #79073 [Com]: round() does not have PHP_ROUND_UP or PHP_ROUND_DOWN modes | ||
| References: | 1 | Groups: | php.bugs |
| Request: | Send a blank email to php-bugs+get-224751@lists.php.net to get a copy of this message | ||
Edit report at https://bugs.php.net/bug.php?id=79073&edit=1
ID: 79073
Comment by: objecttothis at gmail dot com
Reported by: objecttothis at gmail dot com
Summary: round() does not have PHP_ROUND_UP or PHP_ROUND_DOWN
modes
Status: Open
Type: Feature/Change Request
Package: *Math Functions
Operating System: FreeBSD 11.2
PHP Version: 7.4.1
Block user comment: N
Private report: N
New Comment:
@cmb I'll bite. What is the best practice for rounding currency if not a floating calculation?
Perhaps I'm missing something but if I need to get 51.5 percent of $11.01, the result will be
$5.67015. Many times in use the desired rounding would be always up. I really am curious how this
should be done without a floating point calculation.
Previous Comments:
------------------------------------------------------------------------
[2020-01-07 11:39:07] cmb@php.net
> When dealing with currency (accounting, discount calculation,
> etc) this is often needed.
I'd avoid float calculations for currency.
------------------------------------------------------------------------
[2020-01-07 10:55:32] objecttothis at gmail dot com
The result, if these modes were added, would be:
echo round(1234.231,2,PHP_ROUND_UP); //Output 1234.24
echo round(1234.231,2,PHP_ROUND_DOWN); //Output 1234.23
When dealing with currency (accounting, discount calculation, etc) this is often needed.
------------------------------------------------------------------------
[2020-01-07 10:48:54] objecttothis at gmail dot com
Description:
------------
There is no mode in round() that always rounds up or always rounds down. To do this you have to use
ceil() or floor() which do not use precision, so the result will always be an integer. If
PHP_ROUND_UP and PHP_ROUND_DOWN modes were added, it would resolve this problem.
Test script:
---------------
<?php
function round_up($number, $precision = 2)
{
$fig = (int) str_pad('1', $precision, '0');
return (ceil($number * $fig) / $fig);
}
function round_down($number, $precision = 2)
{
$fig = (int) str_pad('1', $precision, '0');
return (floor($number * $fig) / $fig);
}
?>
------------------------------------------------------------------------
--
Edit this bug report at https://bugs.php.net/bug.php?id=79073&edit=1