search
HomeBackend DevelopmentPHP TutorialHow to compare floating point numbers in php?

How to compare floating point numbers in php?

Jul 11, 2017 pm 01:58 PM
phpCompareconduct

Floating point numbers will have errors during the conversion process, so floating point numbers cannot be directly compared in size. Generally, when comparing two floating point numbers, the difference between them is compared. If the difference between the two numbers If it is within an acceptable range, then we consider the two floating point numbers to be equal. This article mainly introduces the php floating point number comparison method, which has a good reference value. Let's take a look at it with the editor

The problem of precision of floating point operations

First look at an example:

<?php
$a = 0.1;
$b = 0.9;
$c = 1;
var_dump(($a+$b)==$c);
var_dump(($c-$b)==$a);
?>

$a+$b== $c returns true, correct
$c-$b==$a returns false, incorrect

Why is this?

After the operation, the actual returned content when the precision is 20 digits is as follows:

<?php
$a = 0.1;
$b = 0.9;
$c = 1;
printf("%.20f", $a+$b); // 1.00000000000000000000
printf("%.20f", $c-$b); // 0.09999999999999997780
?>

$c-$b is 0.09999999999999997780, so it is the same as 0.1 The comparison returns false

This problem occurs because floating point number calculation involves precision. When floating point numbers are converted to binary, precision may be lost.

Floating point number to binary conversion method

The integer part adopts divided by 2 to take the remaindermethod

The decimal part is multiplied by 2 to round method

For example: Convert the number 8.5 to binary

The integer part is 8

##8/2=4 8%2=0

4/2=2 4 %2=0
2/2=1 2%2=0

1 is smaller than 2, so there is no need to calculate it. The binary system of the integer 8 is

1000

The decimal part is 0.5

0.5x2 = 1.0

Since the decimal part is 0 after rounding, there is no need to calculate further

The binary system of decimal 0.5 is 0.1

8.5The binary system of 0.5 is 1000.1

Calculate the number 0.9 Binary

0.9x2=1.8

0.8x2=1.6
0.6x2=1.2
0.2x2=0.4
0.4x2=0.8
0.8x2 =1.6

…. Afterwards, the

loop continues. When the interception accuracy is N, the number after N will be rounded off, resulting in loss of accuracy.

In the above example, the precision of 0.9 is lost when converted to binary, resulting in errors during comparison.

So never believe that a floating point number is accurate to the last digit, and never compare two floating point numbers for equality.

How to correctly compare floating point numbers

1. Use the round method to process and then compare

Example:

<?php
$a = 0.1;
$b = 0.9;
$c = 1;
var_dump(($c-$b)==$a);          // false
var_dump(round(($c-$b),1)==round($a,1)); // true
?>

2. Use high-precision calculation method

When performing calculations first, use high-precision calculation method operation method to ensure that accuracy is not lost.

The method of high-precision operation is as follows:

bcadd Combine two high-precision numbers Addition

bccomp Compares two high-precision numbers and returns -1,0,1

bcp Divide two high-precision numbers

bcmod Find the remainder of a high-precision number

bcmul Multiply two high-precision numbers

bcpow Find the power of a high-precision number

bcpowmod Find the modulus of the power of high-precision numbers

bcscale Configure the default number of decimal points, which is equivalent to Linux in bc ”scale=”

bcsqrt Find the square root of a high-precision number

##bcsub Combine two High-precision number subtractionExample:

<?php
$a = 0.1;
$b = 0.9;
$c = 1;
var_dump(($c-$b)==$a);     // false
var_dump(bcsub($c, $b, 1)==$a); // true
?>

The above is the detailed content of How to compare floating point numbers in php?. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
Optimize PHP Code: Reducing Memory Usage & Execution TimeOptimize PHP Code: Reducing Memory Usage & Execution TimeMay 10, 2025 am 12:04 AM

TooptimizePHPcodeforreducedmemoryusageandexecutiontime,followthesesteps:1)Usereferencesinsteadofcopyinglargedatastructurestoreducememoryconsumption.2)LeveragePHP'sbuilt-infunctionslikearray_mapforfasterexecution.3)Implementcachingmechanisms,suchasAPC

PHP Email: Step-by-Step Sending GuidePHP Email: Step-by-Step Sending GuideMay 09, 2025 am 12:14 AM

PHPisusedforsendingemailsduetoitsintegrationwithservermailservicesandexternalSMTPproviders,automatingnotificationsandmarketingcampaigns.1)SetupyourPHPenvironmentwithawebserverandPHP,ensuringthemailfunctionisenabled.2)UseabasicscriptwithPHP'smailfunct

How to Send Email via PHP: Examples & CodeHow to Send Email via PHP: Examples & CodeMay 09, 2025 am 12:13 AM

The best way to send emails is to use the PHPMailer library. 1) Using the mail() function is simple but unreliable, which may cause emails to enter spam or cannot be delivered. 2) PHPMailer provides better control and reliability, and supports HTML mail, attachments and SMTP authentication. 3) Make sure SMTP settings are configured correctly and encryption (such as STARTTLS or SSL/TLS) is used to enhance security. 4) For large amounts of emails, consider using a mail queue system to optimize performance.

Advanced PHP Email: Custom Headers & FeaturesAdvanced PHP Email: Custom Headers & FeaturesMay 09, 2025 am 12:13 AM

CustomheadersandadvancedfeaturesinPHPemailenhancefunctionalityandreliability.1)Customheadersaddmetadatafortrackingandcategorization.2)HTMLemailsallowformattingandinteractivity.3)AttachmentscanbesentusinglibrarieslikePHPMailer.4)SMTPauthenticationimpr

Guide to Sending Emails with PHP & SMTPGuide to Sending Emails with PHP & SMTPMay 09, 2025 am 12:06 AM

Sending mail using PHP and SMTP can be achieved through the PHPMailer library. 1) Install and configure PHPMailer, 2) Set SMTP server details, 3) Define the email content, 4) Send emails and handle errors. Use this method to ensure the reliability and security of emails.

What is the best way to send an email using PHP?What is the best way to send an email using PHP?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

Best Practices for Dependency Injection in PHPBest Practices for Dependency Injection in PHPMay 08, 2025 am 12:21 AM

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHP performance tuning tips and tricksPHP performance tuning tips and tricksMay 08, 2025 am 12:20 AM

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor