How to convert float to an integer

Source: Internet
Author: User
Weird problem of converting float to an integer for ($ i0; $ I & lt; 10; $ I ++) {$ sum + 0.1 ;}echo & nbsp; (int) $ sum; why is the output 0 instead of 1 shared to: float converted to an integer weird problem
For ($ I = 0; $ I <10; $ I ++ ){
$ Sum + = 0.1;
Echo (int) $ sum;

Why is the output 0 instead of 1?


------ Solution --------------------
Reference Manual

Warnings about floating point precision

Obviously, a simple decimal score is like 0.1 or 0.7. it cannot be converted to an internal binary format without losing a little precision. This will lead to chaotic results: for example, floor (0.1 + 0.7) * 10) usually returns 7 instead of 8 in expectation, because the internal representation of the result is similar to 7. 9999999999999 ....

This is related to the fact that it is impossible to accurately express certain decimal scores with limited digits. For example, decimal 1/3 is changed to 0. 3333333333333 ....

Therefore, never believe that the result of a floating point number is accurate to the last digit, or compare whether the two floating points are equal. If higher precision is required, use any precision mathematical function or gmp function.

Related Article

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: 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.