百科狗-知识改变命运!
--

round() - 对浮点数进行四舍五入 - php 数学函数

百变鹏仔1年前 (2023-11-21)阅读数 22#技术干货
文章标签小数点

round()

(PHP 4, PHP 5, PHP 7)

对浮点数进行四舍五入

说明

round(float $val[,int $precision= 0[,int $mode= PHP_ROUND_HALF_UP]]):float

返回将$val根据指定精度$precision(十进制小数点后数字的数目)进行四舍五入的结果。$precision也可以是负数或零(默认值)。

Note:PHP 默认不能正确处理类似"12,300.2"的字符串。见字符串转换为数值。

参数

$val

要处理的值

$precision

可选的十进制小数点后数字的数目。

$mode

round() - 对浮点数进行四舍五入 - php 数学函数

以下之一:PHP_ROUND_HALF_UPPHP_ROUND_HALF_DOWNPHP_ROUND_HALF_EVENPHP_ROUND_HALF_ODD

返回值

四舍五入后的值

范例

Example #1round()例子

Example #2$mode例子

更新日志

版本说明
5.3.0引入了$mode参数
5.2.7round()的内部运作修改符合 C99 的标准。

参见

  • ceil() 进一法取整
  • floor() 舍去法取整
  • number_format() 以千位分隔符方式格式化一个数字
In my opinion this function lacks two flags:
- PHP_ROUND_UP - Always round up.
- PHP_ROUND_DOWN - Always round down.
In accounting, it's often necessary to always round up, or down to a precision of thousandths. 
If you have negative zero and you need return positive number simple add +0:
$number = -2.38419e-07;
var_dump(round($number,1));//float(-0)
var_dump(round($number,1) + 0);//float(0)
As PHP doesn't have a a native number truncate function, this is my solution - a function that can be usefull if you need truncate instead round a number.

Originally posted in http://stackoverflow.com/a/12710283/1596489
I discovered that under some conditions you can get rounding errors with round when converting the number to a string afterwards.
To fix this I swapped round() for number_format().
Unfortunately i cant give an example (because the number cant be represented as a string !)
essentially I had round(0.688888889,2);
which would stay as 0.68888889 when printed as a string.
But using number_format it correctly became 0.69.
PHP 5.3, 5.4, 5.5

PHP 5.6

PHP 7 
If you'd only want to round for displaying variables (not for calculating on the rounded result) then you should use printf with the float:

This returns: 3.40 .
function mround($val, $f=2, $d=6){
  return sprintf("%".$d.".".$f."f", $val);
}
echo mround(34.89999); //34.90
Here is function that rounds to a specified increment, but always up. I had to use it for price adjustment that always went up to $5 increments. 
This function will let you round to an arbitrary non-zero number. Zero of course causes a division by zero. 
Here's a function to round to an arbitary number of significant digits. Don't confuse it with rounding to a negative precision - that counts back from the decimal point, this function counts forward from the Most Significant Digit.
ex:

Works on negative numbers too. $sigdigs should be >= 0 
Please note that the format of this functions output also depends on your locale settings. For example, if you have set your locale to some country that uses commas to separate decimal places, the output of this function also uses commas instead of dots.
This might be a problem when you are feeding the rounded float number into a database, which requires you to separate decimal places with dots.
See it in action:

The output will be:
3.56
3,56
this function (as all mathematical operators) takes care of the setlocale setting, resulting in some weirdness when using the result where the english math notation is expected, as the printout of the result in a width: style attribute! 
Excel-like ROUNDUP function:
public static function round_up($value, $places) 
{
  $mult = pow(10, abs($places)); 
   return $places 
Unexpected result or misunderstanding (php v5.5.9) 
round() will sometimes return E notation when rounding a float when the amount is small enough - see https://bugs.php.net/bug.php?id=44223 . Apparently it's a feature.
To work around this "feature" when converting to a string, surround your round statement with an sprintf:
sprintf("%.10f", round( $amountToBeRounded, 10));
When you have a deal with money like dollars, you need to display it under this condition:
-format all number with two digit decimal for cents.
-divide 1000 by ,
-round half down for number with more than two decimal
I approach it using round function inside the number_format function:
number_format((float)round( 625.371 ,2, PHP_ROUND_HALF_DOWN),2,'.',',') // 625.37
number_format((float)round( 625.379 ,2, PHP_ROUND_HALF_DOWN),2,'.',',') // 625.38
number_format((float)round( 1211.20 ,2, PHP_ROUND_HALF_DOWN),2,'.',',') // 1,211.20
number_format((float)round( 625 ,2, PHP_ROUND_HALF_DOWN),2,'.',',')   // 625.00
Solving round_down() problem: 
-----------------------------
Use of  fails in some cases, e.g. round_down(2.05, 2) gives incorrect 2.04.
Here is a "string" solution (https://stackoverflow.com/a/26491492/1245149) of the problem (a negative precision is not covered):

Solving round_up() problem:
---------------------------
Use of  fails in some cases, e.g. round_up(2.22, 2) gives incorrect 2.23 (https://stackoverflow.com/a/8239620/1245149).
Adapting the above round_down() "string" solution I have got this result (a negative precision is not covered):

I don't know it is bulletproof, but at least it removes the above mentioned fail. I have done no binary-to-decimal-math-analysis but if `$floorValue + pow(10, 0 - $precision)` works
always as expected then it should be ok.
It should just be noted that what is called "precision" on this page is more correctly called accuracy; precision is the total number of significant digits on both sides of the decimal point, while accuracy is the number of digits to the right of the point. It's a common confusion.
Note that PHP 5.3 didn't just introduce $mode, it rewrote the rounding implementation completely to eliminate many kinds of rounding errors common to rounding floating point values.
That's why round() gives you the correct result even when floor/ceil don't.
For example, floor(0.285 * 100 + 0.5) VS round(0.285*100 + 0.5). First one gives 28, second one gives 29.
More details here: https://wiki.php.net/rfc/rounding
/**
 * Round to first significant digit
 * +N to +infinity
 * -N to -infinity
 *
 */
function round1stSignificant ( $N ) {
 if ( $N === 0 ) {
  return 0;
 }
 $x = floor ( log10 ( abs( $N ) ) );
 return ( $N > 0 )
  ? ceil( $N * pow ( 10, $x * -1 ) ) * pow( 10, $x )
  : floor( $N * pow ( 10, $x * -1 ) ) * pow( 10, $x );
}
echo round1stSignificant( 39144818 ) . PHP_EOL;
echo round1stSignificant( 124818 ) . PHP_EOL;
echo round1stSignificant( 0.07468 ) . PHP_EOL;
echo round1stSignificant( 0 ) . PHP_EOL;
echo round1stSignificant( -0.07468 ) . PHP_EOL;
/**
 * Output
 * 
 * 40000000
 * 200000
 * 0.08
 * 0
 * -0.08
 * 
 */
This functions return ceil($nb) if the double or float value is bigger than "$nb.5" else it's return floor($nb) 
Here is a short neat function to round minutes (hour) ...

You decide to round to nearest minute ...
example will produce : 14:05
In case someone will need a "graceful" rounding (that changes it's precision to get a non 0 value) here's a simple function:
function gracefulRound($val, $min = 2, $max = 4) {
  $result = round($val, $min);
  if ($result == 0 && $min 
To round any number to a given number of significant digits, use log10 to find out its magnitude:

Or when you have to display a per-unit price which may work out to be less than a few cents/pence/yen you can use:

This always displays at least the number of decimal places required by the currency, but more if displaying the unit price with precision requires it - eg: 'English proofreading from $0.0068 per word', 'English beer from $6.80 per pint'.
This function has strange. behaviors:

returns:
141.07
on my machine.
So never really trust this function when you do critical calculations like accounting stuff!
Instead: use only integers or use string comparisons.
Since the mode parameter for options like PHP_ROUND_HALF_UP is available as of PHP 5.3, here is an alternative for ceiling:

If I round this:

You can also use a ceil (which might be useful for pagination):

[Edited by: googleguy@php.net for clarity]
Formats a number to the specified number of significant figures. 
$a = .9;
  $b = .8;
  $d = .1;
  $e = .2;
  $x = $a-$b;
  $y = $e-$d;
  $f = round($x,2);
  echo $f;
  if($f==$y){
    echo "ok";
  }

鹏仔微信 15129739599 鹏仔QQ344225443 鹏仔前端 pjxi.com 共享博客 sharedbk.com

免责声明:我们致力于保护作者版权,注重分享,当前被刊用文章因无法核实真实出处,未能及时与作者取得联系,或有版权异议的,请联系管理员,我们会立即处理! 部分文章是来自自研大数据AI进行生成,内容摘自(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供学习参考,不准确地方联系删除处理!邮箱:344225443@qq.com)

图片声明:本站部分配图来自网络。本站只作为美观性配图使用,无任何非法侵犯第三方意图,一切解释权归图片著作权方,本站不承担任何责任。如有恶意碰瓷者,必当奉陪到底严惩不贷!

内容声明:本文中引用的各种信息及资料(包括但不限于文字、数据、图表及超链接等)均来源于该信息及资料的相关主体(包括但不限于公司、媒体、协会等机构)的官方网站或公开发表的信息。部分内容参考包括:(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供参考使用,不准确地方联系删除处理!本站为非盈利性质站点,本着为中国教育事业出一份力,发布内容不收取任何费用也不接任何广告!)