English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Solution to the inaccuracy of floating-point arithmetic in PHP

Recently, while working on a question about the addition and subtraction of floating-point numbers, a floating-point calculation inaccuracy occurred. It seems that the saying that interpreted languages will have problems with floating-point calculations is indeed true.

First, let's look at a piece of code:

<?php
$a = 0.1;
$b = 0.7;
var_dump(($a + $b) == 0.8);

The printed value is actually boolean false

This is why?PHP manual has the following warning information for floating-point numbers:

Warning

Floating-point precision

It is obvious that simple decimal fractions like 0.1 or 0.7 Cannot be converted to the internal binary format without losing any accuracy. This will cause confusing results: for example, floor((0.1+0.7)*10) usually returns 7 and not as expected 8,because the internal representation of the result is actually similar to 7.9999999999...。

This is related to the fact that it is impossible to express certain decimal fractions precisely using a finite number of digits. For example, the decimal 1/3 It becomes 0.3333333. . .。

So never believe that the result of floating-point numbers is accurate to the last digit, and never compare two floating-point numbers to see if they are equal. If a higher precision is indeed needed, arbitrary precision mathematical functions or gmp functions should be used

Then we should rewrite the above formula as<?php$a = 0.17;var_dump(bcadd($a,$b,2) == 0.8); This will solve the floating-point calculation problem

That's all for the solution to the floating-point calculation problem under PHP that the editor has brought to you. I hope everyone will support and cheer for the tutorial~

You May Also Like