php float浮點型 用round方法比較

<?php
$a = "1.05";
$b = "1.05";
var_dump((floatval($a)== floatval($b)) )//這種比較方法是錯誤的

 

官方解釋 php

$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.web

 

用round 方法來比較app

相關文章
相關標籤/搜索