user619
user619

Reputation: 119

PHP - cast from large float to int will return 0

I can't explain the following behaviour. When casting very large integers (which are handled as floats by PHP) with (int) I get the following results:

<?php
print (int)9223372036854775800;  // returns: 9223372036854775800
echo "<br />";
print (int)11702667999999911110; // returns: -6744076073709639680
echo "<br />";
print (int)17999997999999911110; // returns: -446746073709639680
echo "<br />";
print (int)18400997999999911110; // returns: -45746073709639680
echo "<br />";
print (int)41702667999999999990; // returns: 0
?>

Why does PHP return these values?

Upvotes: 1

Views: 486

Answers (2)

Luis Liz
Luis Liz

Reputation: 1959

You are exceeding the maximum so it's doing that weird stuff from the PHP.net website. You would have to check your max but that looks bigger than 9E18.

The size of an integer is platform-dependent, although a maximum value of about two billion is the usual value (that's 32 bits signed). 64-bit platforms usually have a maximum value of about 9E18. PHP does not support unsigned integers. Integer size can be determined using the constant PHP_INT_SIZE, and maximum value using the constant PHP_INT_MAX since PHP 4.4.0 and PHP 5.0.5.

Upvotes: 4

Orangepill
Orangepill

Reputation: 24645

You are exceeding the value of PHP_INT_MAX which is the largest integer that PHP can support, which is usually 2,147,483,647 on a 32-bit system. Larger numbers are switched over to the float type.

Upvotes: 1

Related Questions