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
$stringvar = "1000.314" ;
$floatvar = floatval ( $stringvar );
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
$stringvar = "1000.314" ;
$floatvar = (float) $stringvar ;
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
$stringvar = "1000.3145635" ;
$floatvar = number_format( $stringvar , 6);
echo "Converted float = " . $floatvar ;
?>
|
Output:
Converted float = 1000.314564
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
30 Apr, 2021
Like Article
Save Article