PHP 日本研討會 2024

bcscale

(PHP 4, PHP 5, PHP 7, PHP 8)

bcscale為所有 bc 數學函式設定或取得預設的小數位數參數

描述

bcscale(int $scale): int

為後續所有未明確指定小數位數參數的 bc 數學函式呼叫設定預設的小數位數參數。

bcscale(null $scale = null): int

取得目前的小數位數。

參數

scale

小數位數。

傳回值

當作為設定器使用時,傳回舊的小數位數。否則傳回目前的小數位數。

錯誤/例外

如果 scale 超出有效範圍,此函式會拋出 ValueError

變更日誌

版本 描述
8.0.0 scale 現在可為 null。
7.3.0 bcscale() 現在可用於取得目前的小數位數;當作為設定器使用時,現在會傳回舊的小數位數值。先前,scale 是強制性的,並且 bcscale() 總是傳回 true

範例

範例 #1 bcscale() 範例

<?php

// 預設小數位數:3
bcscale(3);
echo
bcdiv('105', '6.55957'); // 16.007

// 這和不使用 bcscale() 的情況相同
echo bcdiv('105', '6.55957', 3); // 16.007

?>

新增註解

使用者貢獻註解 4 個註解

23
mwgamera at gmail dot com
16 年前
這些函式不會四捨五入您的值。沒有任何任意精度程式庫會以這種方式執行。它在達到小數位數的精度後停止計算,這表示您的值在小數位數後被截斷,而不是四捨五入。若要進行四捨五入,請使用類似如下的方法
<?php
function bcround($number, $scale=0) {
$fix = "5";
for (
$i=0;$i<$scale;$i++) $fix="0$fix";
$number = bcadd($number, "0.$fix", $scale+1);
return
bcdiv($number, "1.0", $scale);
}
?>
16
sicerwork at aliyun dot com
7 年前
執行 bcsacle() 將會變更 fpm.conf 的小數位數值,而不僅限於目前的程序。
6
ravenswd at gmail dot com
12 年前
使用 rtrim 移除多餘尾隨零的簡單易用方法
<php>
// $total 是 bcmath 計算的結果
if ( strpos($total, '.') !== false )
$total = rtrim($total, '0');
$total = rtrim($total, '.');
endif;
</php>
5
herslyadam at gmail dot com
10 年前
編輯過包含負數支援的 bcround 函式
<?php
function bcround($number, $scale=0) {
if(
$scale < 0) $scale = 0;
$sign = '';
if(
bccomp('0', $number, 64) == 1) $sign = '-';
$increment = $sign . '0.' . str_repeat('0', $scale) . '5';
$number = bcadd($number, $increment, $scale+1);
return
bcadd($number, '0', $scale);
}
?>
To Top