How to correctly convert a PHP string to a numeric value

Source: Internet
Author: User
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.

 
 
  1. < ?php
  2. $foo = 1 + "10.5";
    // $foo is float (11.5)
  3. $foo = 1 + "-1.3e3";
    // $foo is float (-1299)
  4. $foo = 1 + "bob-1.3e3";
    // $foo is integer (1)
  5. $foo = 1 + "bob3";
    // $foo is integer (1)
  6. $foo = 1 + "10 Small Pigs";
    // $foo is integer (11)
  7. $foo = 4 + "10.2 Little Piggies";
    // $foo is float (14.2)
  8. $foo = "10.0 pigs " + 1;
    // $foo is float (11)
  9. $foo = "10.0 pigs " + 1.0;
    // $foo is float (11)
  10. ?>

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.

 
 
  1. < ?php
  2. echo "$foo==$foo; type is " .
    gettype ($foo) . "< br />n";
  3. ?>

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...

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.