I have a unit test that is used to test variable conversions from string to integer. So far it's good, except for the last one.
$_GET['name'] = '42000000000000000000000000000000000000';
$text = $input->get( 'name', Convert::T_INTEGER );
$this->assertEquals( 92233720368547755807, $text );
The expectancy is (which is confirmed by the test itself), is that the large value, when converted from string to integer using intval() causes an overflow which defaults to the largest integer value that php can handle on my system. Yet, it still fails:
Failed asserting that <integer:92233720368547755807> matches expected <double:9.2233720368548E+19>
And when I try to force the expected number into an integer:
$this->assertEquals( intval(92233720368547755807), $text );
I get this:
Failed asserting that <integer:92233720368547755807> matches expected <integer:0>
Which is what the test run literally right before this one tests for...
Relevant code:
public function get( $name, $type = null )
{
$value = $_GET['value'];
if( !is_null( $type ) )
$value = Convert::to( $value, $type );
return $value;
}
And
public static function to( $value, $type )
{
switch( $type )
{
case self::T_INTEGER:
return intval( $value );
default:
return null;
}
}
So开发者_StackOverflow中文版 the question is this: How do I get this test to return positive?
Use the PHP_INT_MAX
constant:
$this->assertEquals( PHP_INT_MAX, $text );
This will fix your problem, AND make your test more portable (e.g. it will work on 32bit systems too).
PHP_INT_MAX's value is the larger representable int
by your PHP build.
See http://php.net/manual/en/reserved.constants.php
You have an extra 5
in your number. This:
92233720368547755807
Should be this:
9223372036854775807
Your problem is, that ever number higher to INT_MAX gets converted to float, which loses precision. If you compare it to String, it always returns false.
Please use bcmath functions for dealing with such large numbers.
精彩评论