Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: intval() equivalent for numbers >= 2147483647

In PHP 5, I use intval() whenever I get numbers as an input. This way, I want to ensure that I get no strings or floating numbers. My input numbers should all be in whole numbers. But when I get numbers >= 2147483647, the signed integer limit is crossed.

What can I do to have an intval() equivalent for numbers in all sizes?

Here's what I want to have:

<?php $inputNumber = 3147483647.37; $intNumber = intvalEquivalent($inputNumber); echo $intNumber; // output: 3147483647 ?> 

Thank you very much in advance!

Edit: Based on some answers, I've tried to code an equivalent function. But it doesn't work exactly as intval() does yet. How can I improve it? What is wrong with it?

function intval2($text) {     $text = trim($text);     $result = ctype_digit($text);     if ($result == TRUE) {         return $text;     }     else {         $newText = sprintf('%.0f', $text);         $result = ctype_digit($newText);         if ($result == TRUE) {             return $newText;         }         else {              return 0;         }     } } 
like image 680
caw Avatar asked Jun 13 '09 09:06

caw


People also ask

What does Intval mean in PHP?

Definition and Usage The intval() function returns the integer value of a variable.

What is int val?

The function intval() gets the integer value of a variable.

Is 0 an integer PHP?

PHP converts the string to an int, which is 0 (as it doesn't contain any number representation).


1 Answers

Try this function, it will properly remove any decimal as intval does and remove any non-numeric characters.

<?php function bigintval($value) {   $value = trim($value);   if (ctype_digit($value)) {     return $value;   }   $value = preg_replace("/[^0-9](.*)$/", '', $value);   if (ctype_digit($value)) {     return $value;   }   return 0; }  // SOME TESTING echo '"3147483647.37" : '.bigintval("3147483647.37")."<br />"; echo '"3498773982793749879873429874.30872974" : '.bigintval("3498773982793749879873429874.30872974")."<br />"; echo '"hi mom!" : '.bigintval("hi mom!")."<br />"; echo '"+0123.45e6" : '.bigintval("+0123.45e6")."<br />"; ?> 

Here is the produced output:

"3147483647.37" : 3147483647 "3498773982793749879873429874.30872974" : 3498773982793749879873429874 "hi mom!" : 0 "+0123.45e6" : 0 

Hope that helps!

like image 134
defines Avatar answered Oct 12 '22 03:10

defines