溫馨提示×

PHP中余數(shù)的四舍五入和截斷技巧

PHP
小樊
84
2024-08-09 20:36:35
欄目: 編程語言

在PHP中,可以使用內(nèi)置函數(shù)round()來對余數(shù)進(jìn)行四舍五入操作。例如:

$number = 10;
$remainder = $number % 3;

// 四舍五入
$rounded_remainder = round($remainder);

echo $rounded_remainder; // 輸出 1

如果想要對余數(shù)進(jìn)行截斷操作,可以使用floor()ceil()函數(shù)。例如:

$number = 10;
$remainder = $number % 3;

// 截斷
$truncated_remainder = $remainder > 0 ? floor($remainder) : ceil($remainder);

echo $truncated_remainder; // 輸出 1

在這里,如果余數(shù)大于0,則使用floor()函數(shù)向下取整,如果余數(shù)小于0,則使用ceil()函數(shù)向上取整。

0