How does the floatval function work?

0

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

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

What is the value that will be printed? Because? Could you tell me more about this function, and about float ?

    
asked by anonymous 30.08.2017 / 19:26

1 answer

1

Brief Introduction to Float

Retrieved from tag :

  

Float is an abbreviation for 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 reliability problem of floating points:

  

Floating-point numbers have Limited precision ... Uncommon mathematical operations may cause major errors, and of course error propagation must be considered when multiple operations are performed made ... So, never rely on results with floating-point numbers to the last house, and never compare floating-point numbers in equalities .

So be careful when using them, whatever your purpose. There are more in-depth questions that take you deeper into this subject that you can find here and here too .

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

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

It will output 152 . By analyzing with var_dump() , you can see that the variable is of type float , with value of 152 .

Parameters

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

float floatval ( mixed $var )

Notes

If you put letters (applicable to the string in general), on 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, the general rule for conversion to floating point .

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

On type conversion, PHP usually already does this for you. That's why you can:

  
  • Write a int and access it as if it were a pointer.
  •   
  • Write a float and access it as a int . It is certain 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.
  •   
  • Write two short in sequence and read as a int . Probably nothing useful will be achieved but it is possible.
  •   
  • Record "SOpt" and read this as a int , I do not know why.
  •   

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

    
30.08.2017 / 19:28