Home >Backend Development >PHP Tutorial >Detailed explanation of round() function in PHP

Detailed explanation of round() function in PHP

autoload
autoloadOriginal
2021-04-20 09:55:014965browse

Detailed explanation of round() function in PHP

In PHP, there are two data types for numbers: Integer integer type and Float floating point type. In some special circumstances, we can only use integer types, and for floating point types, we can only convert them to integer types. PHP provides the round() function , can help us accomplish this task, this article will take you to take a look.

First of all, I must take you to take a look at the syntax of the round() function.

round  ( float $val , int $precision = 0 , int $mode = PHP_ROUND_HALF_UP )
  • $val: Floating point data to be converted

  • $precision: Optional, the number of decimal digits after the decimal point .

  • ##$mode: optional, PHP_ROUND_HALF_UP, PHP_ROUND_HALF_DOWN, PHP_ROUND_HALF_EVEN or PHP_ROUND_HALF_ODD

  • Return value: Return a

    float type Number

Code example:

1. Only one parameter:

<?php
echo round(6.1)."、";
echo round(6.2)."、";
echo round(6.3)."、";
echo round(6.4)."、";
echo round(6.5)."、";
echo round(6.6)."、";
echo round(6.64)."<br>";
输出:6、6、6、6、7、7、7

2. There are two parameters:

<?php
echo round(6.4545,3)."、";
echo round(6.4545,2)."、";
echo round(6.4545,1)."、";
echo round(6.4545,0)."<br>";
?>
输出:6.455、6.45、6.5、6

3. Three parameters:

<?php
echo round(6.65,1,PHP_ROUND_HALF_DOWN)."<br>";//向下取整
echo round(6.65,1,PHP_ROUND_HALF_UP)."<br>";//向上取整
echo round(6.55,1,PHP_ROUND_HALF_EVEN)."<br>";//遇到 .5 的情况时取下一个偶数值舍入$val到 $precision小数位。
echo round(6.55,1,PHP_ROUND_HALF_ODD)."<br>";//遇到 .5 的情况时取下一个奇数值舍入$val到 $precision小数位。

?>
输出:6.6
      6.7
       6.6
       6.5

Recommended: 2021 PHP interview questions summary (collection)》《php video tutorial

The above is the detailed content of Detailed explanation of round() function in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn