php

How to check if a variable is a float in PHP?

Which methods are available in PHP to check if a variable is a float or a double? In this tutorial, we are going to see how to check if a variable is a float in PHP.
 

is_float()

The function is_float($var) returns whether the passed variable is a float or not:

<?php
    var_dump( is_float(1.0) ); // true
    var_dump( is_float(0.000001) ); // true
 
    var_dump( is_float(0) ); // false
    var_dump( is_float(1) ); // false
    var_dump( is_float(true) ); // false
    var_dump( is_float('1.0') ); // false
    var_dump( is_float('hello') ); // false
    var_dump( is_float(new stdClass()) ); // false
?>

Output:

bool(true)
bool(true)
bool(false)
bool(false)
bool(false)
bool(false)
bool(false)
bool(false)
 

Test for float parameters

It makes sense to use is_float() to check function parameters:

<?php
    function myFunction($val) {
        if (!is_float($val)) {
            // Error handling(Exception)
        }
        // ...
    }
?>
PHP MCQ - Multiple Choice Questions and AnswersPHP Questions and Answers – Object-Oriented OOP – Part 1This collection of PHP Multiple Choice Questions and Answers (MCQs): Quizzes & Practice Tests with Answer focuses on “Object-Oriented OOP”.   1. The concept of…Read More mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *