- PHP – How to convert string to float?
- PHP – Convert string to float
- Convert String to Float using Type Casting
- Example
- Convert String to Float using floatval()
- Example
- Conclusion
- floatval
- Return Values
- Changelog
- Examples
- See Also
- User Contributed Notes 23 notes
- Convert String to Float in PHP
- Use the Type Casting to Convert a String to Float in PHP
- Use the floatval() Function to Convert a String to Float in PHP
- Use the number_format() Function to Convert a String to Float in PHP
- Related Article — PHP String
PHP – How to convert string to float?
In this PHP tutorial, you shall learn how to convert a given string to a float value using typecasting or floatval() function, with example programs.
PHP – Convert string to float
To convert string to float in PHP, you can use Type Casting technique or PHP built-in function floatval().
In this tutorial, we will go through each of these methods and learn how to convert contents of a string to a float value.
Convert String to Float using Type Casting
To convert string to floating point number using Type Casting, provide the literal (float) along with parenthesis before the string literal. The expression returns float value of the string.
The syntax to type cast string to float number is
$float_value = (float) $string;
Example
In the following example, we will take a string with floating point number content, and convert the string into float using type casting.
PHP Program
Convert String to Float using floatval()
To convert string to float using PHP built-in function, floatval(), provide the string as argument to the function. The function will return the float value corresponding to the string content.
The syntax to use floatval() to convert string to float is
$float_value = floatval( $string );
Example
In the following example, we will take a string with float content, and convert the string into float value using floatval() function.
PHP Program
Conclusion
In this PHP Tutorial, we learned how to convert a string to float using typecasting and floatval() function.
floatval
May be any scalar type. floatval() should not be used on objects, as doing so will emit an E_WARNING level error and return 1.
Return Values
The float value of the given variable. Empty arrays return 0, non-empty arrays return 1.
Strings will most likely return 0 although this depends on the leftmost characters of the string. The common rules of float casting apply.
Changelog
Version | Description |
---|---|
8.0.0 | The error level when converting from object was changed from E_NOTICE to E_WARNING . |
Examples
Example #1 floatval() Example
$var = ‘122.34343The’ ;
$float_value_of_var = floatval ( $var );
echo $float_value_of_var ; // 122.34343
?>?php
Example #2 floatval() non-numeric leftmost characters Example
See Also
- boolval() — Get the boolean value of a variable
- intval() — Get the integer value of a variable
- strval() — Get string value of a variable
- settype() — Set the type of a variable
- Type juggling
User Contributed Notes 23 notes
This function takes the last comma or dot (if any) to make a clean float, ignoring thousand separator, currency or any other letter :
if (!$sep) return floatval(preg_replace(«/[^0-9]/», «», $num));
>
return floatval(
preg_replace(«/[^0-9]/», «», substr($num, 0, $sep)) . ‘.’ .
preg_replace(«/[^0-9]/», «», substr($num, $sep+1, strlen($num)))
);
>
$num = ‘1.999,369€’;
var_dump(tofloat($num)); // float(1999.369)
$otherNum = ‘126,564,789.33 m²’;
var_dump(tofloat($otherNum)); // float(126564789.33)
you can also use typecasting instead of functions:
There is much easier way to deal with formatted numbers:
$str = ‘13,232.95’ ;
$var = (double) filter_var ( $str , FILTER_SANITIZE_NUMBER_FLOAT , FILTER_FLAG_ALLOW_FRACTION );
var_dump ( $var );
?>
double(13232.95)
To view the very large and very small numbers (eg from a database DECIMAL), without displaying scientific notation, or leading zeros.
FR : Pour afficher les très grand et très petits nombres (ex. depuis une base de données DECIMAL), sans afficher la notation scientifique, ni les zéros non significatifs.
function floattostr ( $val )
preg_match ( «#^([\+\-]|)(5*)(\.(2*?)|)(0*)$#» , trim ( $val ), $o );
return $o [ 1 ]. sprintf ( ‘%d’ , $o [ 2 ]).( $o [ 3 ]!= ‘.’ ? $o [ 3 ]: » );
>
?>
echo floattostr ( «0000000000000001» );
echo floattostr ( «1.00000000000000» );
echo floattostr ( «0.00000000001000» );
echo floattostr ( «0000.00010000000» );
echo floattostr ( «000000010000000000.00000000000010000000000» );
echo floattostr ( «-0000000000000.1» );
echo floattostr ( «-00000001.100000» );
// result
// 1
// 1
// 0.00000000001
// 0.0001
// 10000000000.0000000000001
// -0.1
// -1.1
Easier-to-grasp-function for the ‘,’ problem.
function Getfloat ( $str ) <
if( strstr ( $str , «,» )) <
$str = str_replace ( «.» , «» , $str ); // replace dots (thousand seps) with blancs
$str = str_replace ( «,» , «.» , $str ); // replace ‘,’ with ‘.’
>
if( preg_match ( «#([0-9\.]+)#» , $str , $match )) < // search for number that may contain '.'
return floatval ( $match [ 0 ]);
> else <
return floatval ( $str ); // take some last chances with floatval
>
>
echo Getfloat ( «$ 19.332,35-» ); // will print: 19332.35
?>
function ParseFloat ( $floatString ) <
$LocaleInfo = localeconv ();
$floatString = str_replace ( $LocaleInfo [ «mon_thousands_sep» ] , «» , $floatString );
$floatString = str_replace ( $LocaleInfo [ «mon_decimal_point» ] , «.» , $floatString );
return floatval ( $floatString );
>
?>
setlocale() and floatval() duo could break your DB queries in a very simple way:
setlocale ( LC_ALL , ‘bg_BG’ , ‘bgr_BGR’ );
echo floatval ( 0.15 ); // output 0,15
?>
You would need simple workaround like:
function number2db ( $value )
$larr = localeconv ();
$search = array(
$larr [ ‘decimal_point’ ],
$larr [ ‘mon_decimal_point’ ],
$larr [ ‘thousands_sep’ ],
$larr [ ‘mon_thousands_sep’ ],
$larr [ ‘currency_symbol’ ],
$larr [ ‘int_curr_symbol’ ]
);
$replace = array( ‘.’ , ‘.’ , » , » , » , » );
return str_replace ( $search , $replace , $value );
>
setlocale ( LC_ALL , ‘bg_BG’ , ‘bgr_BGR’ );
$testVal = floatval ( 0.15 ); // result 0,15
var_dump ( $testVal , number2db ( $testVal ));
Most of the functions listed here that deal with $ and , are unnecessarily complicated. You can use ereg_replace() to strip out ALL of the characters that will cause floatval to fail in one simple line of code:
The last getFloat() function is not completely correct.
1.000.000 and 1,000,000 and its negative variants are not correctly parsed. For the sake of comparing and to make myself clear I use the name parseFloat in stead of getFloat for the new function:
function parseFloat ( $ptString ) <
if ( strlen ( $ptString ) == 0 ) <
return false ;
>
$pString = str_replace ( » » , «» , $ptString );
if ( substr_count ( $pString , «,» ) > 1 )
$pString = str_replace ( «,» , «» , $pString );
if ( substr_count ( $pString , «.» ) > 1 )
$pString = str_replace ( «.» , «» , $pString );
$commaset = strpos ( $pString , ‘,’ );
if ( $commaset === false )
$pointset = strpos ( $pString , ‘.’ );
if ( $pointset === false )
$pregResultA = array();
$pregResultB = array();
function testFloatParsing () <
$floatvals = array(
«22 000,76» ,
«22.000,76» ,
«22,000.76» ,
«22 000» ,
«22,000» ,
«22.000» ,
«22000.76» ,
«22000,76» ,
«1.022.000,76» ,
«1,022,000.76» ,
«1,000,000» ,
«1.000.000» ,
«1022000.76» ,
«1022000,76» ,
«1022000» ,
«0.76» ,
«0,76» ,
«0.00» ,
«0,00» ,
«1.00» ,
«1,00» ,
«-22 000,76» ,
«-22.000,76» ,
«-22,000.76» ,
«-22 000» ,
«-22,000» ,
«-22.000» ,
«-22000.76» ,
«-22000,76» ,
«-1.022.000,76» ,
«-1,022,000.76» ,
«-1,000,000» ,
«-1.000.000» ,
«-1022000.76» ,
«-1022000,76» ,
«-1022000» ,
«-0.76» ,
«-0,76» ,
«-0.00» ,
«-0,00» ,
«-1.00» ,
«-1,00»
);
Use this snippet to extract any float out of a string. You can choose how a single dot is treated with the (bool) ‘single_dot_as_decimal’ directive.
This function should be able to cover almost all floats that appear in an european environment.
function float ( $str , $set = FALSE )
<
if( preg_match ( «/([0-9\.,-]+)/» , $str , $match ))
// Found number in $str, so set $str that number
$str = $match [ 0 ];
if( strstr ( $str , ‘,’ ))
// A comma exists, that makes it easy, cos we assume it separates the decimal part.
$str = str_replace ( ‘.’ , » , $str ); // Erase thousand seps
$str = str_replace ( ‘,’ , ‘.’ , $str ); // Convert , to . for floatval command
>
else
// Else, treat all dots as thousand seps
$str = str_replace ( ‘.’ , » , $str ); // Erase thousand seps
return floatval ( $str );
>
>
>
else
// No number found, return zero
return 0 ;
>
>
echo float ( ‘foo 123,00 bar’ ); // returns 123.00
echo float ( ‘foo 123.00 bar’ array( ‘single_dot_as_decimal’ => TRUE )); //returns 123.000
echo float ( ‘foo 123.00 bar’ array( ‘single_dot_as_decimal’ => FALSE )); //returns 123000
echo float ( ‘foo 222.123.00 bar’ array( ‘single_dot_as_decimal’ => TRUE )); //returns 222123000
echo float ( ‘foo 222.123.00 bar’ array( ‘single_dot_as_decimal’ => FALSE )); //returns 222123000
// The decimal part can also consist of ‘-‘
echo float ( ‘foo 123,— bar’ ); // returns 123.00
Convert String to Float in PHP
- Use the Type Casting to Convert a String to Float in PHP
- Use the floatval() Function to Convert a String to Float in PHP
- Use the number_format() Function to Convert a String to Float in PHP
This article will introduce different methods to convert a string to float in PHP.
Use the Type Casting to Convert a String to Float in PHP
We can use type casting to convert one data type to the variable of another data type. Using typecasting, we can convert a string to float in PHP. The correct syntax to use type casting for the conversion of a string to float is as follows.
$floatVar = (float) $stringVar;
This is one of the simplest methods to convert PHP string to float. The program below shows how we can use the type casting to convert a string to float in PHP.
php $mystring = "0.5674"; echo("This float number is of string data type "); echo($mystring); echo("\n"); $myfloat = (float) $mystring; echo("Now, this float number is of float data type "); echo($myfloat); ?>
This float number is of string data type 0.5674 Now, this float number is of float data type 0.5674
Use the floatval() Function to Convert a String to Float in PHP
Another method is to use PHP’s floatval() function to convert a string to float. This function extracts the float value from the passed variable. For example, if the given variable is a string that contains a float value, then this function will extract that value. The correct syntax to use this function is as follows.
This function returns the extracted float value. The program below shows how we can use the floatval() function to convert a string to float in PHP.
php $mystring = "0.5674"; echo("This float number is of string data type "); echo($mystring); echo("\n"); $myfloat = floatval($mystring); echo("Now, this float number is of float data type "); echo($myfloat); ?>
This float number is of string data type 0.5674 Now, this float number is of float data type 0.5674
The function has returned the extracted float value. We have stored this value in $myfloat variable.
Use the number_format() Function to Convert a String to Float in PHP
We can also use the number_format() function to convert a string to float. The number_format() function is used for the formatting of the numbers is a number is passed as a parameter. If we pass a string containing the number as a parameter, it extracts the number from the string first. The correct syntax to use this function is as follows.
number_format($number, $decimals, $decimalpoint, $thousandseperator);
This function returns the formatted float value. The program below shows the ways by which we can use the number_format() function to convert a string to float in PHP.
php $mystring = "0.5674"; echo("This float number is of string data type "); echo($mystring); echo("\n"); $myfloat = number_format($mystring, 4); echo("Now, this float number is of float data type "); echo($myfloat); ?>
This float number is of string data type 0.5674 Now, this float number is of float data type 0.5674
The function has returned the extracted float value. We have stored this value in the $myfloat variable.
Related Article — PHP String
Copyright © 2023. All right reserved