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; } } }
Definition and Usage The intval() function returns the integer value of a variable.
The function intval() gets the integer value of a variable.
PHP converts the string to an int, which is 0 (as it doesn't contain any number representation).
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With