PHP: Calculate the number of digits after the decimal point

Source: Internet
Author: User
Tags count return

This article provides two ways to turn a decimal number into a string and then use the "." To intercept, to go. The length of the substring after. There is a decimal *10, such as the N-second side, such as 10 of 8 times to 8 times to the remainder, and then continue to 10 for the remainder, until the result of 10 remainder is not 0.

In contrast, the first method is much better, for example, 1.000004 at a very border time or 0.99999 such a child PHP processing will have problems, there will be errors, resulting in a different number of digits. And the precision is difficult to grasp, so dealing with this boundary-related problem can finally be done with strings or strings.

First Kind

Private Function _getfloatlength ($num) {
$count = 0;

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

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

return $count;
}

Second Kind

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;
}




Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.