How To Check For Decimal In PHP?

If you wanna check whether the number is in decimal or not, just use the is_float() function.

PHP is_float() function

With PHP function is_float(), you can easily check if the given number is a decimal or not. Just use it in the if-else statement and all done.

<?php
$a = 32;
$b = 32.5;
echo "a is " . is_float($a);
echo "b is " . is_float($b);
?>

//Result will be
a is
b is 1

Using if-else you can format the result or get the desired result in PHP.

Now use the same with the If-Else statement.

<?php
$a = 32.5;
if (is_float($a) == 1)
{
    echo "This is a decimal number.";
}
else
{
    echo "This is not a decimal number.";
}
?>

//Result will be

This is a decimal number.

How to get only decimal values in PHP?

You can separate the decimals. Below you see how we take and separate the decimal value by removing the dot.

Here we have used PHP functions intval, round, substr

intval = Gives you the number without the decimal point.

round = Gives you the number of digits after the decimal points.

substr = Returns a part of a string.

$price = 1234.78;
$whole = intval($price); // 1234
$decimal1 = $price - $whole; // 0.7800000000
$decimal2 = round($decimal1, 2); //0.78
$decimal = substr($decimal2, 2); // 78

Related Posts