Hello~ Today I will continue the previous series of articles on PHP mathematical function practice, so in the previous article "PHP mathematical function practice three: clever use of random function rand()" I introduce to you how to use the rand() function. Friends who are interested can learn about it~
This article brings the fourth practice of PHP mathematical functions! The main content is to explain how to round a floating point number from zero to a specified number of decimal places?
First of all, give you a brief introduction to what floating point numbers are in PHP?
Floating point type (also called floating point number float, double precision number double or real number real) can be defined with any of the following syntax:
<?php $a = 1.234; $b = 1.2e3; $c = 7E-10; $d = 1_234.567; // 从 PHP 7.4.0 开始支持、PHP 7.4.0 之前不支持下划线 ?>
After a brief introduction to floating point numbers, we will go directly Code:
<?php //定义roundout函数 function roundout ($value, $places=0) { if ($places < 0) { $places = 0; } $x= pow(10, $places); return ($value >= 0 ? ceil($value * $x):floor($value * $x)) / $x; } echo roundout (78.78001, 2)."<br>"; echo roundout (8.131001, 2)."<br>"; echo roundout (0.586001, 4)."<br>"; echo roundout (-.125481, 3)."<br>"; echo roundout (-.125481);
The output result is as follows:
78.79 8.14 0.5861 -0.126 -1
So in this code, you need to master several mathematical functions in PHP:
pow()
Function: used to return x raised to the yth power, the syntax is pow(x,y);
;
ceil()
Function: used to round up to the nearest integer, the syntax is ceil(x)
;
Note: Returns the next integer that is not less than x, If x has a decimal part, round it up by one digit. The type returned by ceil() is still float because the range of float values is usually larger than that of integer.
floor()
Function: used to round down to the nearest integer, the syntax is floor(x)
.
Note: Return the next integer not greater than x, and round the decimal part of x. The type returned by floor() is still float because the range of float values is usually larger than that of integer.
PHP Chinese website platform has a lot of video teaching resources. Welcome everyone to learn "PHP Video Tutorial"!
The above is the detailed content of PHP Math Function Practice 4: Round a floating point number from zero to a specified number of decimal places. For more information, please follow other related articles on the PHP Chinese website!