Float checking



In this lesson you will see how to perform type checking for float numbers.

Float numbers, or just "floats", are numbers with a decimal part, like 12.109

To check if a variable is a valid float number, you can use the same filter_var() function, but with a different filter flag: FILTER_VALIDATE_FLOAT.

Let's see how it's done.


Float type checking with filter_var().

You can use filter_var() with float numbers just like you did for integer numbers.

The only difference is that you need to use the FILTER_VALIDATE_FLOAT flag, which makes filter_var() validate floats.


When using the FILTER_VALIDATE_FLOAT flag, filter_var() returns:

  • FALSE, if the variable is not a valid float
  • the value as a PHP float, if it's valid

filter_var() works with both PHP string and numeric types. For example:

The output from the previous code snippet is:

So:

The "not a float" string makes filter_var() return false: bool(false)

All the other elements are valid floats, so filter_var() returns their value as a PHP float: float(123), float(-0.342), and so on.

Note: valid integers, like 123, are also valid floats.




Float notations.

In PHP, floats can also be written using the exponential notation (or scientific notation).

For example, the number 123.456 can also be written as 0.123456e3

Also, when a float number starts with 0, the 0 can be omitted: 0.123 => .123

float_var() accepts all these cases:


This is usually not a problem, but in some cases you may want to keep the variable in the standard float notation, especially if you are using it as a string.

If you want to be sure that the standard notation is used, you can cast the variable into a PHP float and then back into a string again:




Float type checking with is_numeric().

Another PHP function to check float variables is is_numeric().

is_numeric() performs the same checks that filter_var() does (with the FILTER_VALIDATE_FLOAT flag).

The same float values accepted by filter_var() are accepted by is_numeric() too.


is_numeric() is different from filter_var() in two ways:

  • is_numeric() only takes a single argument: the variable to check (there is no flag).
  • is_numeric() simply returns true if the variable is a valid float, or false otherwise.

Since is_numeric() always returns a Boolean value, it's not necessary to use strict comparison on its return value.

Here's an example that shows the difference between the two functions:


Both filter_var() and is_numeric() are secure. You can use the one you prefer.


Lesson takeaways.

  • You can perform type checking on float numbers with filter_var(), using the FILTER_VALIDATE_FLOAT flag.
  • You can also use is_numeric(). filter_var() and is_numeric() perform the same checks.
  • Scientific notation floats are accepted by both functions. If you need the variable to be in the standard notation, convert it into a float and then into a string again.



Complete and Continue  
Discussion

0 comments