今天接到任務需對數字進行計算,涉及整數、小數、科學計數法等諸多條件,人工測試極其麻煩,想到 PHP 單元測試工具 PHPUnit,遂撰寫文件備查。
測試類別 fo,其中 formatn 函數取任意數字的 5 位有效數字:
class fo {
function fo() {}
function formatn($num) {
$num = rtrim($num, "0");
$pos = strpos($num, ".");
$num = str_replace(".", "", $num);
$count1 = strlen($num);
$num = ltrim($num, "0");
$count2 = strlen($num);
$zeroc = $count1 - $count2;
$num = substr($num, 0, 6);
$num = round($num / 10);
if ($pos !== false) {
$num = str_pad($num, (strlen($num) + $zeroc), "0", STR_PAD_LEFT);
$dotl = substr($num, 0, $pos);
$dotr = substr($num, $pos);
$num = $dotl . "." . $dotr;
}
return $num;
}
}