I'm using the following to determine if a value has a decimal. For example $val = 3.3;
if (is_numeric( $val ) && floor( $val ) != $val) {
return true;
}
How can I check of the value's decimal is equal to .3 or greater?
I'm using the following to determine if a value has a decimal. For example $val = 3.3;
if (is_numeric( $val ) && floor( $val ) != $val) {
return true;
}
How can I check of the value's decimal is equal to .3 or greater?
You can subtract floor($val)
from $val
to get the decimal value of $val
. Eg:
if( $val - floor($val) >= 0.3 ) {
return true;
}
Note that it won't work if $val
is negative, you can use abs
for it to work:
if( abs($val) - floor(abs($val)) >= 0.3 ) {}
Or something like:
// if the negative number should be greater than 0.3
if( $val - floor($val) >= 0.3 && abs($val) - floor(abs($val)) >= 0.3 ) {}
// if the negative number should be less than 0.3
if( $val - floor($val) >= 0.3 && abs($val) - floor(abs($val)) <= 0.3 ) {}
Ty this:
function fractionalPartOfDoubleVal($doub){
// $doub = +1.4;
// $whole = floor($doub);
if ($doub > 0){
$whole = floor($doub);
} else {
$whole = ceil($doub);
}
$fractionalPart = $doub - $whole;
if ($fractionalPart > 0.3){
// further processing
}
return abs($fractionalPart);
}
$posFractionalPart = fractionalPartOfDoubleVal(2.7);
echo ($posFractionalPart);
$negFractionalPart = fractionalPartOfDoubleVal(-2.7);
echo ($negFractionalPart);
You can get the integer part of your float, and subtract it from the original:
$value = 3.3;
$integer = floor($value); // 3
$decimal = $value - $integer; //0.3
if($decimal >= 0.3){ //true
//your stuff
}