Analysis of Two float (floating point number) comparison instances in PHP

Source: Internet
Author: User
This article mainly introduces two float (floating point number) comparisons in PHP, and analyzes the use skills of the bccomp function for floating point number comparison in the form of a complete example, which has some reference value, for more information about how to compare two float (floating point number) methods in PHP, see the following example. Share it with you for your reference. The details are as follows:

Recently, when I was developing a contract management system, two floating point numbers were involved, which made me miserable.
A long time ago, N did not know where to hear a "truth" that "do not use equal signs to compare floating-point numbers". he was using it at ordinary times. It seemed that there was no problem, but this problem finally came.

<? Php $ sum = "12300.00"; $ a = "10000.30"; $ B = "2000.30"; $ c = "299.40"; $ sum = (float) $ sum; $ s = (float) ($ a + $ B + $ c); var_dump ($ sum, $ s); var_dump ($ sum = $ s );

The result is:

Float (12300)
Float (12300)
Bool (false)

Later I learned that in PHP, to compare the two floating point numbers, we can use bccomp (parameter 1, parameter 2, decimal place) to compare them.

<? Php $ sum = "12300.00"; $ a = "10000.30"; $ B = "2000.30"; $ c = "299.40"; $ sum = (float) $ sum; $ s = (float) ($ a + $ B + $ c); var_dump ($ sum, $ s); var_dump (bccomp ($ sum, $ s, 2 ));

Result:

Float (12300)
Float (12300)
Int (0) // 0 indicates that two floating point values are equal

For details about how to use the bccomp function, refer to the PHP Manual.

I hope this article will help you with php programming.

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.