Horje
How to Convert Int Number to Double Number in PHP ?

In PHP, working with numeric data types is a common task, and sometimes you might need to convert an integer (int) to a double (float). In this article, we will explore various approaches to achieve this conversion in PHP, covering different methods based on the PHP version and use cases.

Method 1: Using Type Casting

One basic way to convert an integer to a double is by using type casting. PHP allows you to explicitly cast a variable to a different type using the (float) or (double) cast.

PHP

<?php
  
// Original integer value
$intValue = 42;
  
// Convert to double using type casting
$doubleValue = (float)$intValue;
  
// Display the result
echo "Integer: $intValue, Double: $doubleValue";
  
?>

Output

Integer: 42, Double: 42

Method 2: Using floatval() Function

The floatval() function is designed to explicitly convert a variable to a float. It is a concise and readable alternative to type casting.

PHP

<?php
  
// Original integer value
$intValue = 42;
  
// Convert to double using floatval() function
$doubleValue = floatval($intValue);
  
// Display the result
echo "Integer: $intValue, Double: $doubleValue";
  
?>

Output

Integer: 42, Double: 42

Method 3: Implicit Conversion

In PHP, operations involving integers and floating-point numbers often result in implicit conversion. When an integer is used in a context where a floating-point number is expected, PHP automatically performs the conversion.

PHP

<?php
  
// Original integer value
$intValue = 42;
  
// Implicit conversion to double
$doubleValue = $intValue + 0.0;
  
// Display the result
echo "Integer: $intValue, Double: $doubleValue";
  
?>

Output

Integer: 42, Double: 42

Method 4: Using settype() Function

The settype() function in PHP allows you to set the type of a variable explicitly. While less common, it is another approach to convert an integer to a double.

PHP

<?php
  
// Original integer value
$intValue = 42;
  
// Convert to double using 
// settype() function
settype($intValue, 'float');
  
// Display the result
echo "Double: $intValue";
  
?>

Output

Double: 42



Reffered: https://www.geeksforgeeks.org


Geeks Premier League

Related
What are HTML Tags ? What are HTML Tags ?
How to Count Occurrences of Each Word in Given Text File in PHP ? How to Count Occurrences of Each Word in Given Text File in PHP ?
23 Times Table | Learn Multiplication Table of 23 Online 23 Times Table | Learn Multiplication Table of 23 Online
HCF of 92 and 152 | How to Find HCF of 92 and 152 HCF of 92 and 152 | How to Find HCF of 92 and 152
LCM of 24 and 36 | How to Find LCM of 24 and 36 LCM of 24 and 36 | How to Find LCM of 24 and 36

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
15