Detect round number in PHP?
How can 开发者_高级运维I find out whether a float in PHP is a round number?
is_round(1.5); // false
is_round(1.0); // true
is_round(1.00000001); // false
Modification to Rob's code regarding sterofrog's comment. Code checks to ensure the value is also numeric.
function is_round($value) {
return is_numeric($value) && intval($value) == $value;
}
function is_round( $value ) {
return intval( $value ) == $value;
}
A much shorter version: !fmod($num,1)
in PHP or this in JS: !($num % 1)
As a (more readable) function:
function is_round( $num ) {
return !fmod($num, 1);
}
This works on the basis that any number that's not exactly 0 is falsey. You can use fmod($num,1)
to get the decimals of a number; once you have those you can just !
them.
The function specified on this page by thierryreeuwijk should specify your needs.
if ($value = round($value))
Should work.
精彩评论