Home > php教程 > php手册 > PHP:计算小数点后位数

PHP:计算小数点后位数

WBOY
Release: 2016-06-21 08:48:00
Original
1611 people have browsed it

本文提供两种方法,一种将小数变成字符串,然后用”.“来截取,去.后的子字符串长度。还有一种是讲小数*10的N次方,比如10的8次方再对8次方取余数,再不断对10求余,直到对10求余的结果不为0。

相比来说,第一种方法要好不少,理由是这样的,比如1.000004在很边界的时候或者0.99999这样子PHP处理会有问题,会有误差,导致得到的位数不一样。而且精度难以把握,所以处理这种跟边界有关的问题最后能用字符串还是字符串来做。

第一种

private function _getFloatLength($num) {
$count = 0;

$temp = explode ( '.', $num );

if (sizeof ( $temp ) > 1) {
$decimal = end ( $temp );
$count = strlen ( $decimal );
}

return $count;
}
Copy after login

第二种

function getfloatlength($a){
	if(($a-(int)$a)<1E-9){
		$count=0;
	}
	$a=fmod(1E9*$a,1E9);
	while($a%10==0){
		if($a==0)break;
		$a=$a/10;
		$count--;
	}
	return count;
}
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 Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template