1、通过截取取整(如果整数部分过大,会有问题)
/**
* 对价格进行向上取整
* @param $price 价格
* @param $decimal 保留小数位数
*/
function upDecimal($price, $decimal = 2){
$data1 = pow(10, $decimal);
$data2 = ceil(bcmul($price, $data1,10));
$data3 = bcdiv($data2, $data1, $decimal);
return $data3;
}
2、字符串取整
/**
* 对价格进行向上或向下取整
* @param $price 价格
* @param $decimal 保留小数位数
* @param $type 1:向上 2:向下
*/
function upDecimal($num, $dec = 2, $type = 1){
if($num != 0){
$numArr = explode('.',$num);
if($type == 1){
if($num > 0){
if($numArr[1][$dec] > 0){
$numArr[1][$dec-1] = $numArr[1][$dec-1]+1;
}
}
}else{
if($num < 0) {
if ($numArr[1][$dec] > 0) {
$numArr[1][$dec - 1] = $numArr[1][$dec - 1] + 1;
}
}
}
$numArr[1] = substr($numArr[1], 0, $dec);
$var = implode('.', $numArr);
return $var;
}
return $num;
}
3.完美
/** * 对价格进行向上或向下取整 * @param $price 价格 * @param $decimal 保留小数位数 * @param $type 1:向上 2:向下 */ function upDecimal($num, $qty = 2, $type = 1){ $num2 = explode('.', $num); $dcmnum = $num2[1] ?? 0; $subnum = 0; if($dcmnum > 0){ $subnum = bcsub(strlen($dcmnum), $qty, 10); } $powint = bcpow(10, $qty); $num = bcmul($num, $powint, $subnum); $numArr = explode('.', $num); $num = $numArr[0]; $dcm = $numArr[1] ?? 0; if($dcm > 0){ if($type == 1 && $num > 0){ $num = $num + 1; }elseif($type == 2 && $num < 0){ $num = $num - 1; } } return bcdiv($num, $powint, $qty); }