2014-04-22 3 views
-1

11.5에서 30 % 할인을 계산하는 다음 PHP 스크립트를 실행할 때. 나는 이상한 결과를 얻을 것이다. 일반적으로 계산 된 결과를 테스트 할 때 조건이 false가 될 것으로 예상됩니다. 하지만 대신 사실이됩니다.PHP에서 숫자를 계산할 때 이상한 동작이 발생했습니다.

이 경우 PHP로 무엇이 잘못 되었습니까?

<?php 
$_discount = 30; 
$_price = 11.5; 
$_qty = 1; 

echo $_result = ((1-$_discount/100) * $_price); // the result is 8.05 
echo $_result; // prints 8.05; 
echo gettype($_result); // prints double 

echo $_result !== 8.05; // returns 1 instead of 0 
?> 
+1

['GMP()를'] (http://www.php.net/manual/en/ref.gmp.php) 기능을 위해 사용하십시오 부동 연산. –

+0

플로트를 비교하는 것에 대해 SO에 대해 많은 질문이있었습니다. [this] (http://stackoverflow.com/questions/3148937/compare-floats-in-php) 및 [this] (http://stackoverflow.com/questions/3148937/compare-floats-in-php)은 단지 두 가지 예입니다. PHP 샌드 박스의 경우 [php.net] (http://www.php.net/manual/en/language.types.float.php) –

답변

2

봅니다 this를 사용 :

<?php 
$_discount = 30; 
$_price = 11.5; 
$_qty = 1; 

echo $_result = ((1-$_discount/100) * $_price); // the result is 8.05 
echo $_result; // prints 8.05; 
echo gettype($_result); // prints double 

echo (double)$_result !== 8.05; 
?> 
+0

+1을 참조하십시오. 그러나 코드를 실행하면 '1'이 반환됩니다. . –

관련 문제