Home > Backend Development > PHP Problem > How to convert string to number in php (three methods)

How to convert string to number in php (three methods)

PHPz
Release: 2023-04-10 11:10:03
Original
3868 people have browsed it

In PHP, a string can be coerced into a number. This is usually used when the input string needs to be converted into a numeric type for calculation.

  1. Using casts

In PHP, you can use casts to convert a string into a number. Casting uses a plus sign ( ) to convert a string. For example:

$str = "123";
$int = (int)$str;
Copy after login

This will cast the string "123" to the integer value 123 and save it in the variable $int.

  1. Use function conversion

PHP also provides some functions for converting strings to numeric types. The most common of these are the intval() and floatval() functions.

intval() function can convert a string into an integer. For example:

$str = "123";
$int = intval($str);
Copy after login

This will also convert the string "123" to the integer value 123.

floatval() function can convert a string to a floating point type. For example:

$str = "3.14";
$float = floatval($str);
Copy after login

will convert the string "3.14" to the floating point value 3.14.

In addition, PHP also provides some other functions for converting strings to other numeric types. For example, the doubleval() function can convert a string to a double-precision floating point type, while the octdec() and hexdec() functions can convert a string to an octal and hexadecimal integer value respectively.

Summary

In PHP, you can convert a string to a numeric type using cast or function conversion. Different functions work with different types of numbers. Using these functions can not only ensure the accuracy of type conversion, but also avoid errors caused by improper type conversion.

The above is the detailed content of How to convert string to number in php (three methods). For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template