PHP two float (floating point) comparison case analysis _php skills

Source: Internet
Author: User

This example describes two float (floating-point) comparison methods in PHP. Share to everyone for your reference. Specifically as follows:

In the recent development of a contract management system, involving two floating point number comparison, I was depressed.
In the N long ago, do not know where to listen to a "Do not use equal sign to compare floating point" of the "truth", their usual use, as if there is no problem, but this problem is finally come.

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

Float (12300)
Float (12300)
BOOL (FALSE)

I later learned that in PHP, to compare the size of two floating-point numbers, you can use Bccomp (parameter 1, parameter 2, decimal places) to compare.

<?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));

Results:

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

The Bccomp function can refer to the PHP manual in particular.

I hope this article will help you with your PHP program design.

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.