|
|
|
เรื่องปัดทศนิยมครับ คือถ้า 1.50 มันจะแสดงแค่ 1.5 ครับ ผมอยากให้ มันแสดง 1.50 ครับ |
|
|
|
|
|
|
|
Code (PHP)
<?
echo "1.005 round 2 ตำแหน่ง แบบ half up แล้วได้ = ".aphalfup(1.005,2)."<br/>";
echo "1.005 round 2 ตำแหน่ง แบบ half down แล้วได้ = ".aphalfdown(1.005,2)."<br/>";
function aphalfup($num, $precision)
{
return apprec($num, $precision, "halfup");
}
function aphalfdown($num, $precision)
{
return apprec($num, $precision, "halfdown");
}
function apprec($num, $precision, $roundmode)
{
$num = "$num";
if ($num == "INFINITY" || $num == "-INFINITY") return $num;
if ($precision < 0) $precision = 0; // negative precision not allowed
if ($roundmode == "halfup") $atleast = "5";
else if ($roundmode == "floor") $atleast = "a";
else if ($roundmode == "halfdown") $atleast = "6";
else if ($roundmode == "ceiling") $atleast = "1";
else $atleast = "5"; // all other modes mean halfup
$result = bcadd("$num", "0", $precision + 1);
$result = apcorrectsign($result);
$lastdigit = substr($result, -1);
if ($lastdigit >= $atleast)
{
if (bccomp($result, "0", BCCOMP_PRECISION) == -1) $one = -1;
else $one = 1;
$pow = bcpow("10", "-$precision", $precision);
$addend = bcmul($pow, "$one", $precision);
$result = bcadd($result, $addend, $precision);
return $result;
}
$result = bcadd($result, "0", $precision);
$result = apcorrectsign($result);
return $result;
}
function apcorrectsign($num)
{
$num = "$num";
if ($num == "INFINITY" || $num == "-INFINITY") return $num;
if (substr($num, 0, 1) == "-")
{
$unsigned = substr($num, 1);
if (bccomp($unsigned, "0", BCCOMP_PRECISION) == 0)
{
return substr($num, 1);
}
return $num;
}
return $num;
}
?>
ลองเอาไปใช้ดูครับ
|
|
|
|
|
Date :
2010-02-05 13:27:44 |
By :
windersun |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Load balance : Server 01
|