PHP: calculates the number of digits after the decimal point

Source: Internet
Author: User

This article provides two methods, one is to convert the decimal number into a string, and then use "." To intercept, remove the length of the. substring. Another method is to explain the N power of decimal * 10. For example, to the power of 10, the remainder is obtained for the power of 8, and then the remainder is continuously obtained for 10, until the result of 10 is not 0.

In comparison, the first method is much better. The reason is that, for example, when 1.000004 is at a very boundary or 0.99999, PHP processing may have problems and errors, resulting in different digits. The accuracy is hard to grasp, so we can use strings or strings to solve this boundary-related problem.

First

Private function _ getFloatLength ($ num) {$ count = 0; $ temp = explode ('. ', $ num); if (sizeof ($ temp)> 1) {$ decimal = end ($ temp); $ count = strlen ($ decimal );} return $ count ;}

Second

Function getfloatlength ($ a) {if ($ a-(int) $ a) <1E-9) {$ count = 0 ;}$ a = fmod (1E9 * $, 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.