Home >Backend Development >PHP Tutorial >数字四舍五入的有关问题

数字四舍五入的有关问题

WBOY
WBOYOriginal
2016-06-13 12:08:58974browse

数字四舍五入的问题
比如$a=1.2;
echo $a;    //这里我要让它显示为1.5

$a=1.6;
echo $a;    //这里我要让它显示为2

也就是说,当$a的小数点后面的值小于5时(不包括0),就按5来显示,小数点后面的值大于5时就按正常的四舍五入
------解决思路----------------------

<br />function test($val){<br />	$x=explode('.',sprintf("%.1f", $val));<br />	$a=$x[0];<br />	$d=$x[1];<br />	if($d>0 && $d<5){<br />		$r=$a+0.5;<br />	}else{<br />		$r=round($val);<br />	}<br />	return $r;<br />}<br /><br />echo test(1);//1<br />echo test(1.11);//1.5<br />echo test(1.5);//2<br />echo test(1.6);//2<br />

------解决思路----------------------
需求要说清楚
for($i=1; $i<2; $i+=0.1)<br />  printf("%.1f : %s\n", $i, ceil($i * 2) / 2);<br />
1.0 : 1<br />1.1 : 1.5<br />1.2 : 1.5<br />1.3 : 1.5<br />1.4 : 1.5<br />1.5 : 2<br />1.6 : 2<br />1.7 : 2<br />1.8 : 2<br />1.9 : 2<br /><br />

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn