Open In App

How to convert String to Float in PHP ?

Last Updated : 30 Apr, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

Strings in PHP can be converted to float very easily. In most use cases, it won’t be required since PHP does implicit type conversion. There are many methods to convert a string into a number in PHP, some of them are discussed below:

Methods:

  • Using floatval() function.
  • Using Typecasting.
  • Using number_format() function.

Method 1: Using floatval() function.

Note: The floatval() function can be used to convert the string into float values .

Syntax:

$floatvar = floatval($stringvar)

Return Value: This function returns a float. This float is generated by typecasting the value of the variable passed to it as a parameter.

Example:

PHP




<?php
  
  // Number in string format
  $stringvar = "1000.314";
  
  // converts string into float
  $floatvar floatval($stringvar);
  
  // prints the value of above variable as a float
  echo "Converted float = ".$floatvar;
  
?>


Output:

Converted float = 1000.314

Method 2: Using Typecasting.

Note:  Typecasting is the explicit conversion of data type because the user explicitly defines the data type in which he wants to cast. We convert String into Float.

Syntax:

$floatvar = (float)$stringvar

Example:

PHP




<?php
  
// Number in string format
$stringvar = "1000.314";
  
// converts string into float
$floatvar =  (float)$stringvar;
  
// prints the value of above variable as a float
echo "Converted float = ".$floatvar;
  
?>


Output:

Converted float = 1000.314

Method 3: Using number_format() function.

Note: The number_format() function is an inbuilt function in PHP that is used to format a number with grouped thousands. It returns the formatted number on success otherwise it gives E_WARNING on failure.

Syntax:

string number_format( $number, $decimals, $decimalpoint, $sep )

Return Value: It returns a formatted number in case of success, otherwise it gives E_WARNING if it fails.

Example:

PHP




<?php
  
// Number in string format
$stringvar = "1000.3145635";
  
// converts  string into float with 6 decimals
$floatvar =  number_format($stringvar, 6);
  
// prints the value of above variable as a string
echo "Converted float = ".$floatvar;
  
?>


Output:

Converted float = 1000.314564


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads