The floatval()
variable handling function can be used to convert a string to a floating point number (aka float, double, or real number).
Syntax
= floatval();
The returned float value on successful conversion, or 0 on failure. Empty arrays will return 0 and non-empty arrays will return 1. See examples below.
(var parameter)
Required parameter that accepts multiple data types. It is a scalar value being converted to an integer.
Examples
Code snippets in examples below have been tested in PHP parser version 5.5.36.
String Conversion
= floatval();
| statement |
|
---|---|---|
"37.5" | = floatval("37.5"); | 37.5 |
"37.0" | = floatval("37.0"); | 37 |
"37" | = floatval("37"); | 37 |
"37e3" | = floatval("37e3"); | 3700 |
"37E3" | = floatval("37E3"); | 3700 |
"37e-3" | = floatval("37e-3"); | 0.0037 |
"37E-3" | = floatval("37E-3"); | 0.0037 |
"+37" | = floatval("+37"); | 37 |
"-37" | = floatval("-37"); | -37 |
"0b100101" | = floatval("0b100101"); | 0 |
"037" | = floatval("037"); | 37 |
"0x25" | = floatval("0x25"); | 0 |
"37 coins" | = floatval("37 coins"); | 37 |
"37%" | = floatval("37%"); | 37 |
"37C" | = floatval("37C"); | 37 |
"X37" | = floatval("X37"); | 0 |
Number Conversion
= floatval();
| statement |
|
---|---|---|
37.5 | = floatval(37.5); | 37.5 |
37.0 | = floatval(37.0); | 37 |
37 | = floatval(37); | 37 |
37e3 | = floatval(37e3); | 3700 |
37E3 | = floatval(37E3); | 3700 |
37e-3 | = floatval(37e-3); | 0.0037 |
37E-3 | = floatval(37E-3); | 0.0037 |
+37 | = floatval(+37); | 37 |
-37 | = floatval(-37); | -37 |
0b100101 | = floatval(0b100101); | 37 1) |
037 | = floatval(037); | 55 2) |
045 | = floatval(045); | 37 2) |
0x37 | = floatval(0x37); | 55 3) |
0x25 | = floatval(0x25); | 37 3) |
1) Value for precedes with 0b indicating binary (base 2) notation (available since PHP parser version 5.4.0).
2) Value for precedes with 0 indicating octal (base 8) notation.
3) Value for precedes with 0x indicating hexadecimal (base 16) notation.
Array Conversion
= floatval();
| statement |
|
---|---|---|
array() | = floatval(array()); | 0 |
array("x", "y", "z") | = floatval(array("x", "y", "z")); | 1 |
Rounding Precision
Some decimal numbers, such as 0.1 or 0.7, do not have an exact representation as a binary number and can not be converted to their binary counterparts without a small loss of precision. Hence, some rounding errors must be expected when coding. E.g., try this:
= "9 m";
= "6.9 m";
if (floatval() - floatval() == 2.1) {
echo floatval()." - ".floatval()." = 2.1";
}
else {
echo floatval()." - ".floatval()." ≠ 2.1";
}