In PHP programming, the ceil() function is a commonly used mathematical function that rounds a number upward, that is, returns the smallest integer greater than or equal to the number. The function is defined as follows:
float ceil ( float $value )
Usually, the arguments of the ceil() function are a numeric type, or a string that can be automatically converted to a numeric by PHP. But what happens if the incoming Chinese characters or illegal strings? This article will explore in detail how the ceil() function performs under such inputs and how it deals with non-numeric inputs.
Simple call example:
<?php
echo ceil(4.2); // Output 5
echo ceil(-3.7); // Output -3
?>
ceil() rounds the floating point number upwards, pay attention to the processing of negative numbers. The result of rounding upwards is an integer with a larger value (such as -3.7 rounding upwards to -3).
<?php
echo ceil("Chinese"); // ?
echo ceil("abc123"); // ?
echo ceil("123abc"); // ?
?>
PHP will try to convert the function parameters in type, and the parameters received by ceil() will be converted into floats . During the conversion process, PHP will try to parse numeric characters from the beginning of the string, and stop converting when the first illegal numeric character is encountered. If the beginning of the string cannot be converted to a number, the result is 0.
The specific manifestations are as follows:
"Chinese" : The beginning of the string is a non-numeric character, and converted to a floating point number to 0, so the result of ceil("Chinese") is 0.
"abc123" : Also starts with a non-number, the conversion result is 0, and returns 0.
"123abc" : The string starts with the number 123. When a is encountered, the conversion is stopped and converted to 123. The result of ceil("123abc") is 123.
Sample code:
<?php
var_dump(ceil("Chinese")); // float(0)
var_dump(ceil("abc123")); // float(0)
var_dump(ceil("123abc")); // float(123)
?>
Output:
float(0)
float(0)
float(123)
Although PHP allows implicit conversions of the above types, in actual projects, passing non-numeric strings to ceil() should be avoided to avoid unexpected results.
Use is_numeric() to detect whether the input is a number :
<?php
$input = "Chinese";
if (is_numeric($input)) {
echo ceil($input);
} else {
echo "The input is not a number,Unable to sort";
}
?>
Use filter_var() for stricter filtering :