PHP typecasting float-> int

Given this PHP code:

// total is 71.24 (float) $value = $total * 100; var_dump($value); $valuecast = (int)$value; var_dump($valuecast); settype($value, 'int'); var_dump($value); 

var_dump ($ value) gives float (7124)

var_dump ($ valuecast) gives int (7123)

var_dump ($ value) after settype gives int (7123)

How can I get the correct type conversion?

+4
casting types php
Jan 13 '10 at 9:01
source share
2 answers

For float to int, I suggest round . This should take into account the inaccuracy of the IEEE float.

+2
Jan 13 2018-10-13T00: 00Z
source share
— -

From the PHP manual on TypeCasting Float to Integer

Attention

Never add an unknown fraction to an integer, as this can sometimes lead to unexpected results.

 <?php echo (int) ( (0.1+0.7) * 10 ); // echoes 7! ?> 

See also float precision warning .

+4
Jan 13 '10 at 9:08
source share



All Articles