Home  >  Article  >  Backend Development  >  PHP uses round, ceil, and floor functions to round floating-point decimals (example)

PHP uses round, ceil, and floor functions to round floating-point decimals (example)

不言
不言Original
2018-07-19 11:00:362678browse

Sometimes when using division operations, some numbers may not be divisible, but if we want to get the integer part of the result, then what functions can we use to solve this problem.

1. round - round floating point numbers

float round (float $val [, int $precision])

Return val according to Specifies the precision (number of decimal digits after the decimal point) for rounding results. precision can also be negative or zero (default).
//Example #1 round() Example

<?php  
echo round(3.4); // 3  
echo round(3.5); // 4  
echo round(3.6); // 4  
echo round(3.6, 0); // 4  
echo round(1.95583, 2); // 1.96  
echo round(1241757, -3); // 1242000  
echo round(5.045, 2); // 5.05  
echo round(5.055, 2); // 5.06  
?>

Note: PHP cannot handle strings like "12,300.2" correctly by default. See Convert String to Numeric.

2. ceil - further rounding (rounding up)

float ceil (float $value)

Returns not less than value The next integer, value is rounded up by one if there is a decimal part. The type returned by ceil() is still float, because the range of float values ​​is usually larger than that of integer.
//Example #1 ceil() Example

<?php  
echo ceil(4.3); // 5  
echo ceil(9.999); // 10  
?>

3. floor - rounding by rounding (rounding down)

float floor (float $value)

Returns the next integer that is not greater than value, and rounds the decimal part of value. The type returned by floor() is still float, because the range of float values ​​is usually larger than that of integer.
//Example #1 floor() Example

<?php  
echo floor(4.3); // 4  
echo floor(9.999); // 9  
?>

Related recommendations:

phpFloating point numbers rounded to integer

Several methods of rounding in php

The above is the detailed content of PHP uses round, ceil, and floor functions to round floating-point decimals (example). 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