Google News
logo
PHP Program to Cast float and string to integer
In PHP, you can cast a float or a string to an integer using the `(int)` cast operator.

Here's an example :
Program :
<?php
// Cast a float to an integer
$float_num = 3.14;
$int_num = (int) $float_num;
echo "Float: $float_num, Integer: $int_num<br>";

// Cast a string to an integer
$string_num = "42";
$int_num = (int) $string_num;
echo "String: $string_num, Integer: $int_num<br>";
?>
Output :
Float: 3.14, Integer: 3
String: 42, Integer: 42
In this example, the variable `$float_num` is assigned the value `3.14`. The `(int)` cast operator is used to cast `$float_num` to an integer, which is assigned to the variable `$int_num`. The message "Float: 3.14, Integer: 3" will be printed.

The variable `$string_num` is assigned the value `"42"`. The `(int)` cast operator is used to cast `$string_num` to an integer, which is assigned to the variable `$int_num`. The message "String: 42, Integer: 42" will be printed.

It's important to note that when casting a string to an integer, PHP will attempt to parse the string as an integer value. If the string cannot be parsed as an integer, the result of the cast will be `0`.