Home  >  Article  >  Backend Development  >  Analysis of unexpected situations during int conversion of intval() in php

Analysis of unexpected situations during int conversion of intval() in php

WBOY
WBOYOriginal
2016-07-25 08:58:271446browse
This article introduces an abnormal situation encountered when using intval() to convert int in PHP, and its solution for your reference.

Test code for php’s intval() function:

<?php
/**
* intval()进行int转换
* edit bbs.it-home.org
*/
$a = 9.45*100;  
var_dump($a);  
var_dump(intval($a));  
  
$a = 945*1.00;  
var_dump($a);  
var_dump(intval($a));  
?>
html code:

Operating results: float(945) int(944) float(945) int(945)

Explain: The number 9.45 looks like this when we see it, but it is not this inside the machine, but 9.449999999999999999... so: 9.449999*100 = 944.9999. intval directly removes the mantissa. In this way, intval is almost the same as the floor() function. This was something I hadn't noticed before. Didn't notice that intval will be rounded down. There is no such thing as 1.0099999 in 1.00, so 945*1.00 will have a float of 945. Then the intval transformation will naturally avoid the situation of 944. There are also some classic exam questions, such as: intval((0.1+0.7)*10) is equal to 7 instead of 8. This is all true.

How about this, the introduction is here, you understand the intval() function of php.



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