Pyh.conf’25: a new PHP conference for the Russian-speaking community

Voting

: max(one, eight)?
(Example: nine)

The Note You're Voting On

udochen at gmail dot com
18 years ago
Code below implements standard rounding on 5 or higer round up, else don't round. There wasn't a round function for the BC functions, so here is a simple one that works. Same args as round, except takes strings and returns a string for more BC operations.

----------------

function roundbc($x, $p) {

$x = trim($x);
$data = explode(".",$x);

if(substr($data[1],$p,1) >= "5") {

//generate the add string.
$i=0;
$addString = "5";
while($i < $p) {
$addString = "0" . $addString;
$i++;
}//end while.
$addString = "." . $addString;

//now add the addString to the original fraction.
$sum = bcadd($data[0] . "." . $data [1],$addString,$p+1);

//explode the result.
$sumData = explode(".",$sum);

//now, return the correct precision on the rounded number.
return $sumData[0] . "." . substr($sumData[1],0,$p);

} else {

//don't round the value and return the orignal to the desired
//precision or less.
return $data[0] . "." . substr($data[1],0,$p);

}//end if/else.

}//end roundbc.

<< Back to user notes page

To Top