How to correctly convert a PHP string to a numeric value. When a string is evaluated as a number, the result type and value are determined according to the following rules. If any of the characters include., e, or E, the string is treated as float.When a string is evaluated as a number, the result type and value are determined according to the following rules.
If the string contains any of the characters ".", "e", or "E", it is evaluated as a float. Otherwise, it is treated as an integer.
This value is determined by the first part of the string. If a string starts with a valid digital data, use this number as its value. Otherwise, its value is 0 (zero ). Valid numeric data starts with an optional plus or minus sign, followed by one or more numbers (including decimal scores), followed by an optional index. Flying Asp! The technology park Index is an "e" or "E" followed by one or more numbers.
- < ?php
- $foo = 1 + "10.5";
// $foo is float (11.5)
- $foo = 1 + "-1.3e3";
// $foo is float (-1299)
- $foo = 1 + "bob-1.3e3";
// $foo is integer (1)
- $foo = 1 + "bob3";
// $foo is integer (1)
- $foo = 1 + "10 Small Pigs";
// $foo is integer (11)
- $foo = 4 + "10.2 Little Piggies";
// $foo is float (14.2)
- $foo = "10.0 pigs " + 1;
// $foo is float (11)
- $foo = "10.0 pigs " + 1.0;
// $foo is float (11)
- ?>
To test any example of converting a PHP string to a numeric value in this section, copy and paste the example and add the following line to see what will happen.
- < ?php
- echo "$foo==$foo; type is " .
gettype ($foo) . "< br />n";
- ?>
Do not expect to get the encoding of a character when converting it into an integer (it may also be done in C ). If you want to convert a PHP string to a numeric value between character encoding and character, use the ord () and chr () functions.
Bytes. If any of the characters include., e, or E, the string is treated as float...