How does the floatval function work?

Asked

Viewed 667 times

1

I saw in the PHP documentation that there is a function called floatval(), to take the floating point value of a variable. Then I saw on the internet a question similar to this one on the internet:

$value = '152a.35678';
$value = floatval($value);
echo $value;

What value will be printed? Why? Could you explain more about this function, and about float?

1 answer

2


Brief Introduction to Float

Taken from the tag :

Float is an abbreviation of Floating Point Number (Floating point number). And in most programming languages, this type is used for variables with decimal values, such as 0.1 or 15.0025.

Float in PHP

In PHP there is a problem in reliability of floating points:

Floating point numbers have limited precision ... Unusual mathematical operations may cause errors and, of course, the spread of errors should be considered when several operations are carried out ... So never trust results with floating point numbers to the last house, and never compare floating point numbers on equalities.

So you’d better be careful using them, whatever your goal is. There are questions with more details, which address more deeply this subject that you can find here and here too.


The function floatval() PHP, as explained in documentation, is the floating point value of a given variable. And in this case:

$value = '152a.35678';
$value = floatval($value);
echo $value; //imprime 152

Will generate the output from 152. Analyzing with var_dump(), you can see that the variable is of type float, with value of 152.

Parameters

The function floatval() receives a single parameter, which is the value you want to get it in floating point.

float floatval ( mixed $var )

Notes

If you put letters (applicable to string in general), to the left will be returned 0.

$var = 'The122.34343';
$float_value_of_var = floatval($var);
echo $float_value_of_var; // imprime 0

But if you add in the end, it will try to apply, to general rule of floating point conversion.

$variavel = '122.34343The';
$valor_float = floatval ($variavel);
echo $valor_float; // imprime 122.34343

About type conversion, PHP usually already does this for you. That’s why you get it:

  • Record a int and access it as if it were a pointer.
  • Record a float and access as if it were a int. It is true that the result will be catastrophic in this case, but it is possible.
  • Get a 0 and be considered false or other numbers (no matter what type) be interpreted as true in operations that require a boolean.
  • Record two short in sequence and read as a int. Probably nothing useful will be obtained but it is possible.
  • Record "Sopt" and read this as if it were a int, I don’t know why.

PHP which is a weakly typed language allows this. You can read more on strong typing and weak here.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.