Home > Backend Development > PHP Tutorial > Comparison example analysis of two float (floating point numbers) in PHP_php skills

Comparison example analysis of two float (floating point numbers) in PHP_php skills

WBOY
Release: 2016-05-16 20:07:22
Original
1107 people have browsed it

The example in this article describes two float (floating point number) comparison methods in PHP. Share it with everyone for your reference. The details are as follows:

When I was developing a contract management system recently, it involved comparing two floating point numbers, which made me very depressed.
A long time ago, I didn’t know where I heard the “truth” of “Don’t use the equal sign to compare floating point numbers”. I used it on a daily basis, and it seemed that there was no problem. But this time the problem finally came.

<&#63;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);

Copy after login

The result is:

float(12300)
float(12300)
bool(false)

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

<&#63;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));

Copy after login

Result:

float(12300)
float(12300)
int(0) // 0 means two floating point values ​​are equal

For specific usage of the bccomp function, please refer to the PHP manual.

I hope this article will be helpful to everyone’s PHP programming design.

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template