数字四舍五入的问题

WBOY
Release: 2016-06-23 13:46:41
Original
1052 people have browsed it

比如$a=1.2;
echo $a;    //这里我要让它显示为1.5

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

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


回复讨论(解决方案)

$n = 1.2;//$n = 1.6;$t = explode('.', "$n");$n = $t[1]{0} < 5 ? $t[0] + .5 : round($n);echo $n;
Copy after login
Copy after login

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

function fn($num) {
return ceil($num * 2) / 2;
}

$n = 1.2;//$n = 1.6;$t = explode('.', "$n");$n = $t[1]{0} < 5 ? $t[0] + .5 : round($n);echo $n;
Copy after login
Copy after login



如果$n=1.5 //则还是显示1.5

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



用了这个方法

需求要说清楚

for($i=1; $i<2; $i+=0.1)  printf("%.1f : %s\n", $i, ceil($i * 2) / 2);
Copy after login
Copy after login
1.0 : 11.1 : 1.51.2 : 1.51.3 : 1.51.4 : 1.51.5 : 21.6 : 21.7 : 21.8 : 21.9 : 2
Copy after login
Copy after login

function fn($num) {
return ceil($num * 2) / 2;
}



+1

$arr = array(1.0,1.1,1.2,1.3,1.4,1.5,1.6,1.7,1.8,1.9,2.0,2.1);foreach($arr as $v){	echo $v.' -> '.fn($v).'<br>';}function fn($num){	return ($ret=round($num, 0))>=$num? $ret : $ret+0.5;}
Copy after login


1 -> 1
1.1 -> 1.5
1.2 -> 1.5
1.3 -> 1.5
1.4 -> 1.5
1.5 -> 2
1.6 -> 2
1.7 -> 2
1.8 -> 2
1.9 -> 2
2 -> 2
2.1 -> 2.5

需求要说清楚

for($i=1; $i<2; $i+=0.1)  printf("%.1f : %s\n", $i, ceil($i * 2) / 2);
Copy after login
Copy after login
1.0 : 11.1 : 1.51.2 : 1.51.3 : 1.51.4 : 1.51.5 : 21.6 : 21.7 : 21.8 : 21.9 : 2
Copy after login
Copy after login


经典啊!!!!!
Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template