简体   繁体   中英

How do i round php number by half?

if my number is 4.9 then i want it to round to 4.5

if 4.6 then i want 4.5

if 4.3 then i want 4

if 3.5 then it stays the same at 3.5

if 2 then stays at the same at 2

The closest thing I found is round( $num, 1, PHP_ROUND_HALF_UP); and that's not exactly what I want. Thanks

You can use floor()

$num = floor($num * 2) / 2

If you want to round up or down then you can use round()

$num = round($num * 2) / 2

there is no built in function with those weird rounding rules, you'll have to write it yourself. like

function myweirdround($f){
$i=(int)$f;
$remainder=$f-$i;
if($remainder===0.9){
return $i+0.5;
}
if($remainder===0.6){return $i+0.5;}
if($remainder===0.3){return $i;}
if($remainder===0.5){return $f;}
return $f;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM