search
HomeBackend DevelopmentPHP TutorialAnalysis of the pitfalls of PHP and JS floating point operations

javascript

Why is 0.1 + 0.2 not equal to 0.3? (Correct result: 0.30000000000000004)

Why is 0.8 * 7 not equal to 5.6? (Correct result: 5.6000000000000005)

PHP

var_dump(intval(0.58 * 100));

The correct result is 57, not 58

The trouble caused by floating point operations

Actually, these results are not language bugs, but are related to the implementation principle of the language. All numbers in js are unified as Number, including integers, which are actually all double precision (double) types.

And PHP will distinguish between int and float. No matter what language, as long as floating point operations are involved, there are similar problems, so you must pay attention when using them.

Floating point binary principle

According to the international standard IEEE 754, any binary floating point number V can be expressed in the following form:

V = (-1)s * M * E 

    1. (-1)s 表示符号位,当s=0,V为正数;当s=1,V为负数。
    2. M表示有效数字,大于等于1,小于2。
    3. 2E 表示指数位。

For example: decimal -5.0 , written in binary is -101.0, which is equivalent to -1.01×22. Then, s=1, M=1.01, E=2.
IEEE 754 stipulates that for a 32-bit floating point number, the highest 1 bit is the sign bit s, the next 8 bits are the exponent E, and the remaining 23 bits are the significant digit M.

Analysis of the pitfalls of PHP and JS floating point operations

For a 64-bit floating point number, the highest 1 bit is the sign bit S, the next 11 bits are the exponent E, and the remaining 52 bits are the significant digit M.

Analysis of the pitfalls of PHP and JS floating point operations

IEEE 754 also has some special provisions for the significant digit M and the exponent E.

As mentioned before, 1≤M

As for the index E, the situation is more complicated.

First of all, E is an unsigned integer (unsigned int). This means that if E is 8 bits, its value range is 0~255; if E is 11 bits, its value range is 0~2047. However, we know that E in scientific notation can be a negative number, so IEEE 754 stipulates that the real value of E must be subtracted from E by an intermediate number. For an 8-bit E, this intermediate number is 127; for 11 The middle number is 1023.
For example, the E of 210 is 10, so when it is saved as a 32-bit floating point number, it must be saved as 10 (the real value of E) + 127 = 137 (E), which is 10001001.

Then, the index E can be further divided into three situations:
(1) E is not all 0 or not all 1. At this time, the floating point number is represented by the above rules, that is, the calculated value of the exponent E is subtracted from 127 (or 1023) to obtain the real value, and then the first 1 is added before the significant digit M.
(2)E is all 0. At this time, the exponent E of the floating point number is equal to 1-127 (or 1-1023), and the effective digit M no longer adds the first 1, but is reduced to a decimal of 0.xxxxxx. This is done to represent ±0, and very small numbers close to 0.
(3)E is all 1. At this time, if the significant digits M are all 0, it means ± infinity (the sign bit depends on the sign bit s); if the significant digits M are not all 0, it means that the number is not a number (NaN). >

The above is the detailed content of Analysis of the pitfalls of PHP and JS floating point operations. 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
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

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 Article

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.