Example analysis of PHP's method of converting string into number

  • 2021-11-13 06:56:20
  • OfStack

Here are four ways PHP converts strings into numbers.

Method 1:

Use the number_format () function. The number_format () function is used to convert a string to a number. It returns a formatted number on success, or E_WARNING on failure.


<?php 
  
$num = "1000.314"; 
  
//  Use number_format() Function converts a string to a number 
echo number_format($num), "\n"; 
  
//  The function does the : Convert a string to a number 
echo number_format($num, 2); 
?>

Output:


1,000
1,000.31

Method 2:

Use type conversion: Type conversion can directly convert strings to float, double, or integer primitive types. This is the best way to convert strings to numbers without using any functions.

Example:


<?php 
  
//  Numbers in string format  
$num = "1000.314"; 
  
//  Use int Type conversion 
echo (int)$num, "\n"; 
  
//  Use float  Type conversion  
echo (float)$num, "\n"; 
  
//  Use double  Type conversion 
echo (double)$num; 
?>

Output:


1000
1000.314
1000.314

Method 3:

Use the intval () and floatval () functions. The intval () and floatval () functions can also be used to convert strings to their corresponding integers and floating-point values, respectively.

Example:


<?php 
  
//  Numbers in string format  
$num = "1000.314"; 
  
// intval The function does the : Convert a string to an integer 
echo intval($num), "\n"; 
  
// floatval The function does the : Convert a string to a floating point number 
echo floatval($num); 
?>

Output:


1000
1000.314

Method 4:

By adding 0 or performing a mathematical operation. You can also convert string numbers to integers or floating-point numbers by adding 0 to the string. In PHP, strings are implicitly converted to integers or floating-point numbers when performing mathematical operations.


<?php 
    
//  Convert numbers to string format 
$num = "1000.314"; 
  
//  Perform mathematical operations on implicit type conversions  
echo $num + 0, "\n"; 
  
//  Perform mathematical operations on implicit type conversions 
echo $num + 0.0, "\n"; 
  
//  Perform mathematical operations on implicit type conversions 
echo $num + 0.1; 
?>

Output:


1000.314
1000.314
1000.414


Related articles: