-3

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?

CyberJunkie
  • 21,596
  • 59
  • 148
  • 215
  • 2
    Can the 5 users with 1000+ rep perhaps try searching for a duplicate instead of answering? – CodeCaster Mar 12 '18 at 13:58
  • 2
    Programming is breaking up a larger problem into smaller steps which you can solve separately. Once you have the decimal part of a number, comparing that decimal part to the desired number is trivial. It's almost as easy as putting two and two together. Read [ask] and show your research. – CodeCaster Mar 12 '18 at 14:00

3 Answers3

5

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 ) {}
Aniket Sahrawat
  • 12,410
  • 3
  • 41
  • 67
1

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);
Hektor
  • 1,845
  • 15
  • 19
0

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
}
Phiter
  • 14,570
  • 14
  • 50
  • 84