Last updated on September 22, 2023
There are two available ways in PHP for converting float value into integer, in which first is the intval() function and (int). Let’s create a variable for juice price and assign float value to it.
$juicePrice = 4.50;
echo $juicePrice;
// Output: 4.5
To make sure if the $juicePrice
variable data type is float, we can check its type through the var_dump() function.
// check type of $juicePrice
var_dump($juicePrice);
// Output: float(4.5)
The var_dump() function returns the float data type of juice variable. In the next step, we need to convert it into integer, to do that we can use casting.
So create a new variable $convertIntoInteger
, then assign it to the previously created variable $juicePrice
along with (int) that converts the data type.
$convertIntoInteger = (int)$juicePrice;
echo $convertIntoInteger;
// Output: 4
Here the (int) converts the $juicePrice
value into an integer which is assigned to the $convertIntoInteger
.
Convert Float Value to Integer Through intval() Function
It can be converted through intval() function too. To convert the float value into an integer, pass the value as an argument in the PHP built-in function intval(). The intval() function accepts two parameters: the first is required and the second is optional. The value needed to convert into an integer should be passed into the first parameter.
Below is an example,
$convertIntoInteger = intval($juicePrice);
echo $convertIntoInteger;
// Output: 4
So we have converted the integer value in $convertIntoInteger
, we can make sure by passing as argument into var_dump() function. Below is an example,
// check type of $convertIntoInteger
var_dump($convertIntoInteger);
// Output: int(4)
This article demonstrates conversion of float values into integers in PHP. In this article we have used (int) and intval() functions for converting float value into integer.