PHP7 Mining Pit: Floating-point data comparison

Source: Internet
Author: User

Today, a strange problem is encountered in the project, and the result is a comparison of two variables with equal values for the computed double type of the variable, but the results are not equal.


<?php$a=42735.04; $b =17806.2; $c = $a/36; $c =round ($c, 2); $d = $c *15;echo ' $b value is: '. $b. " \ n "; Echo ' $d value is: '. $d. " \ n ", if ($b = = $d) {echo" ok\n ";} else{echo "sorry\n";}


The results are as follows, the value of two variables is the same, do ' = = ' comparison operation but return false

650) this.width=650; "src=" https://s3.51cto.com/wyfs02/M00/9B/CB/wKioL1lnLTOCGkbJAAAoYDhHs7w497.jpg "style=" float : Left; "title=" php7compare.jpg "alt=" Wkiol1lnltocgkbjaaaoydhhs7w497.jpg "/>




The reason is that the precision has changed after a series of operations such as/,*,round () in the floating-point numbers in PHP7.


Solution: Compare any variable of any precision as a string.


A better solution has been provided in the PHP7.

(PHP 4, PHP 5, PHP 7) bccomp-compare two arbitrary-precision numeric descriptions int Bccomp (string $left _operand, String $right _operand[, int $scale = int]) Compares Right_operand and Left_operand, and returns the result of an integer.



Finally use Bccomp () to compare and resolve the problem

if (Bccomp (String) $b, (String) $d, 2) = = = 0) {echo "Yes \ n";} else{echo "no \ n";}



This article is from the "My PHP path" blog, so be sure to keep this source http://phpme.blog.51cto.com/663593/1947237

PHP7 Mining Pit: Floating-point data comparison

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.