How to Convert String to Integer and Float in PHP

When working with strings, you may sometimes need to convert them to numbers. For example, if you’re reading a value from a user input field, you’ll need to convert it to a number before using it in any mathematical operations.

Fortunately, PHP makes this easy with the built-in functions intval() and floatval(). The intval() function converts a string to an integer. If the string doesn’t contain a valid number, it will return 0. The floatval() function converts a string to a floating-point number. If the string doesn’t contain a valid number, it will return 0.0.

We can use type cast operator (int) or (float) as an alternative to intval() and floatval(). However, these functions are preferred because they give more flexibility.

$string = '12.34 Dollars';
$int = intval($string); //12
$float = floatval($string); //12.34

$string = '$12.34 Dollars'; //not starting with a number
$int = intval($string); //0
$float = floatval($string); //0.0

$string = "150.99";
$int = (int) $string; //150
$float = (float) $string; //150.99

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.