在 PHP 中對浮點數進行取整
在 PHP 中,round()
函式對浮點數進行舍入。本教程演示如何使用 PHP 的 round()
函式。
在 PHP 中舍入浮點數
round()
函式對 PHP 中的浮點數進行舍入。我們可以使用它來定義一個特定的精度值,該值將四捨五入,保持精度值在檢視中。
此精度值可以為零或負數。該函式有三個引數;這個函式的語法是:
float round(number, precision, mode);
在哪裡:
-
number
是我們要四捨五入的浮點數。 -
precision
是一個可選引數,它決定要舍入到的小數位數。預設的precision
值為零。 -
mode
是一個可選引數,用於指定一個常數,指定舍入模式。模式常量有四種型別:3.1.
PHP_ROUND_HALF_UP
:此模式將告訴方法將數字從零舍入。
3.2.PHP_ROUND_HALF_DOWN
:此模式將告訴方法將數字舍入為零。
3.3.PHP_ROUND_HALF_EVEN
:此模式將告訴方法將數字舍入到最接近的偶數值。
3.4.PHP_ROUND_HALF_ODD
:此模式將告訴方法將數字舍入到最接近的奇數值。
此方法的返回值是四捨五入的數字。讓我們試試這個方法的一個例子。
<?php
$RoundValue1=round(10.3);
$RoundValue2=round(12.5);
$RoundValue3=round(13.6);
$RoundValue4=round(14.6,0);
$RoundValue5=round(6.97553,2);
$RoundValue6=round(7.76521,-3);
$RoundValue7=round(8.063,2);
$RoundValue8=round(9.076,2);
$RoundValue9=round(6.97553, PHP_ROUND_HALF_UP);
$RoundValue10=round(6.97553, PHP_ROUND_HALF_DOWN);
$RoundValue11=round(6.97553, PHP_ROUND_HALF_EVEN);
$RoundValue12=round(6.97553, PHP_ROUND_HALF_ODD) ;
echo "The Round Value for (10.3) is : ". $RoundValue1 . "<br /><br />" ;
echo "The Round Value for (12.5) is : ". $RoundValue2 . "<br /><br />" ;
echo "The Round Value for (13,6) is : ". $RoundValue3 . "<br /><br />" ;
echo "The Round Value for (14.6,0) is : ". $RoundValue4 . "<br /><br />" ;
echo "The Round Value for (6.97553,2) is : ". $RoundValue5 . "<br /><br />" ;
echo "The Round Value for (7.76521,-3) is : ". $RoundValue6 . "<br /><br />" ;
echo "The Round Value for (8.063,2) is : ". $RoundValue7 . "<br /><br />" ;
echo "The Round Value for (9.076,2) is : ". $RoundValue8 . "<br /><br />" ;
echo "The Round Value for (6.97553,2, PHP_ROUND_HALF_UP) is : ". $RoundValue9 . "<br /><br />" ;
echo "The Round Value for (6.97553,2, PHP_ROUND_HALF_DOWN) is : ". $RoundValue10 . "<br /><br />" ;
echo "The Round Value for (6.97553,2, PHP_ROUND_HALF_EVEN) is : ". $RoundValue11 . "<br /><br />" ;
echo "The Round Value for (6.97553,2, PHP_ROUND_HALF_ODD) is : ". $RoundValue12 . "<br /><br />" ;
?>
上面的程式碼顯示了 round()
方法的 12 個不同版本的用法。檢視輸出:
The Round Value for (10.3) is : 10
The Round Value for (12.5) is : 13
The Round Value for (13,6) is : 14
The Round Value for (14.6,0) is : 15
The Round Value for (6.97553,2) is : 6.98
The Round Value for (7.76521,-3) is : 0
The Round Value for (8.063,2) is : 8.06
The Round Value for (9.076,2) is : 9.08
The Round Value for (6.97553,2, PHP_ROUND_HALF_UP) is : 7
The Round Value for (6.97553,2, PHP_ROUND_HALF_DOWN) is : 6.98
The Round Value for (6.97553,2, PHP_ROUND_HALF_EVEN) is : 6.976
The Round Value for (6.97553,2, PHP_ROUND_HALF_ODD) is : 6.9755
Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.
LinkedIn Facebook