Home > Software engineering >  How to check given number is decimal or not in laravel?
How to check given number is decimal or not in laravel?

Time:11-21

I want to check weather given number is decimal or not if it's decimal it should return decimal or else it should return integer.

I tried many solutions from the internet it's failing some conditions, please help me to acheive this thing.

It should return decimal if it's this format also 10.00, 10.0 ,99.000 .

$value=$request->amount;//99.99,99.00...
if(gettype($value)){
 if(decimal){
 //My logic goes here.
}
if(integer){
//My logic
}
}

CodePudding user response:

Here is what you want:

$value=$request->amount;

if(fmod($value, 1) !== 0.00){
    //It is decimal, so the decimal logic goes here.
} else {
    // It is an Intereger, so the ineteger logic goes here.
}

fmod(x,y) is a PHP function that returns the remainder of x/y.

You simply set y=1, the number (here is x) is an Integer only if the remainder of x/1 equals 0.00.

For example:

the output of fmod(10.05,1) is 0.05 so it is decimal the output of fmod(5,1) is 0 so it is an integer

If you want to learn more about fmod function, pay a visit to fmod function description

Note: you can even pass a string to fmod function and it will automatically change to a number.

For example:

the output of fmod('34.04',1) is 0.04 and it is decimal

CodePudding user response:

You can get most of what you want from is_float, but if you really need to know whether it has a decimal in it, you can use the following function:

function is_decimal( $val )
{
    return is_numeric( $val ) && is_float( $val ) != $val;
}
  • Related