PHP Undefined Constant PHP_ROUND_HALF_DOWN

血红的双手。 提交于 2019-12-07 04:38:13

问题


I have some PHP code in a project I'm working on that uses PHP's round function. On my localhost, I don't include any quotes around my mode argument, stating it as just PHP_ROUND_HALF_DOWN. However, when pushing to my server I get the error message:

Use of undefined constant PHP_ROUND_HALF_DOWN - assumed 'PHP_ROUND_HALF_DOWN'
Warning (2): Wrong parameter count for round() [APP/views/helpers/time_left.php, line 14]

Now, when I add the single quotes to the mode argument, the first error goes away, however the "wrong parameter count" remains. I'm calling the function as follows:

$days = round(($difference/$day), 0, PHP_ROUND_HALF_DOWN);

Thanks for any and all help!


回答1:


The rounding mode was added in PHP 5.3. Make sure you're running at least that version.

You can see which version you're running by placing the following in a PHP file:

var_dump(phpversion());



回答2:


The mode argument was only added in PHP 5.3.0. If you're running an earlier version of PHP, then the mode option constants (PHP_ROUND_HALF_UP, PHP_ROUND_HALF_DOWN, PHP_ROUND_HALF_EVEN, and PHP_ROUND_HALF_ODD) won't be defined

EDIT

You can't use the mode argument for round() prior to 5.3.0, but you can achieve the equivalent by combining functions:

round(floor($value * 100) / 100,2); //  to round down to 2dp
round(floor($value * 1000) / 1000,3); //  to round down to 3dp
round(ceil($value * 100) / 100,2); //  to round up to 2dp



回答3:


PHP_ROUND_HALF_DOWN requires PHP 5.3.0 as seen here: http://php.net/manual/en/math.constants.php

You're probably on a lower PHP version.




回答4:


round() defaults to using PHP_ROUND_HALF_UP but you can only change it in PHP >= 5.3.0

To emulate PHP_ROUND_HALF_DOWN I think you can subtract (1/10^(precision+1))*5 from the number before rounding.

to put it simply;

<?php
  $number=20.005;
  $precision=2;
  echo round($number,$precision);                         //20.01
  echo round($number-(1/10^($precision+1))*5,$precision); //20.00
  echo round($number-0.005,2);                            //20.00
?>



回答5:


What version of PHP is running on your server? According to the docs only PHP 5.3 or greater supports the PHP_ROUND constants.




回答6:


Is PHP_ROUND_HALF_DOWNsupported by your version?

According to the documentation mode wasnt introduced till 5.3

5.3.0    The mode parameter was introduced.

You can use floor instead (or ceil if you want to go the other way)




回答7:


$mode was added on PHP 5.3

check php's version with:

php -v

edit: or use php's phpinfo() procedure

cheers



来源:https://stackoverflow.com/questions/4948373/php-undefined-constant-php-round-half-down

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!