Сравнение чисел с плавающей точкой

$x = 8 — 6.4; // which is equal to 1.6
$y = 1.6;
var_dump($x == $y); // is not true

PHP thinks that 1.6 (coming from a difference) is not equal to 1.6. To make it work, use round()

var_dump(round($x, 2) == round($y, 2)); // this is true

This happens probably because $x is not really 1.6, but 1.599999.. and var_dump shows it to you as being 1.6.

false
$a = 8 — 6.4;
$b = 1.6;
$c = $a == $b;
// Способ 1: округляем в большую сторону до 2х знаков после запятой и сравниваем -> true
$aa = round($a, 2);
$bb = round($a, 2);
$cc = $aa == $bb;
// Способ 2: получаем модуль разности и сравниваем с допустимым отклонение -> true
$ab = abs($a — $b);
$cab = $ab < 0.01; var_dump(compact('a', 'b', 'c', 'aa', 'bb', 'cc', 'ab', 'cab')); /** * array (size=8) * 'a' => float 1.6
* ‘b’ => float 1.6
* ‘c’ => boolean false
* ‘aa’ => float 1.6
* ‘bb’ => float 1.6
* ‘cc’ => boolean true
* ‘ab’ => float 4.4408920985006E-16
* ‘cab’ => boolean true
*/

Добавить комментарий

Ваш e-mail не будет опубликован.