PHP Doku:: Konvertiert einen Wert nach float - function.floatval.html

Verlauf / Chronik / History: (1) anzeigen

Sie sind hier:
Doku-StartseitePHP-HandbuchFunktionsreferenzVariablen- und typbezogene ErweiterungenVariablenbehandlungFunktionen zur Behandlung von Variablenfloatval

Ein Service von Reinhard Neidl - Webprogrammierung.

Funktionen zur Behandlung von Variablen

<<empty

get_defined_vars>>

floatval

(PHP 4 >= 4.2.0, PHP 5)

floatvalKonvertiert einen Wert nach float

Beschreibung

float floatval ( mixed $var )

Konvertiert var nach float.

Parameter-Liste

var

Kann jeder skalare Typ sein. floatval() kann nicht auf Arrays oder Objekte angewandt werden.

Rückgabewerte

Der float-Wert der übergebenen Variable.

Beispiele

Beispiel #1 floatval()-Beispiel

<?php
$var 
'122.34343The';
$float_value_of_var floatval($var);
echo 
$float_value_of_var// 122.34343
?>

Siehe auch


15 BenutzerBeiträge:
- Beiträge aktualisieren...
secretr at NOSPAM dot e107 dot org
3.01.2011 17:37
setlocale() and floatval() duo could break your DB queries in a very simple way:

<?php
setlocale
(LC_ALL, 'bg_BG', 'bgr_BGR');
echo
floatval(0.15); // output 0,15
?>

You would need simple workaround like:

<?php
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));

// Result:
// float(0,15)
// string(4) "0.15"
?>
balai01 at yahoo dot com
13.10.2010 12:56
//changes comma to dot if any
//removes any currency symbol and gets the floatVar

$price_fl_point=(preg_replace("/,/",".",$price));
$price_c=floatval(preg_replace("/^[^0-9\.]/","",$price_fl_point));
chris at georgakopoulos dot com
29.07.2009 17:12
locale aware floatval:

<?php
function ParseFloat($floatString){
   
$LocaleInfo = localeconv();
   
$floatString = str_replace($LocaleInfo["mon_thousands_sep"] , "", $floatString);
   
$floatString = str_replace($LocaleInfo["mon_decimal_point"] , ".", $floatString);
    return
floatval($floatString);
}
?>
ted devito
10.03.2009 6:10
i noticed all (well, unless i missed something) the functions working with decimals destroy trailing decimal places. this function restores them in case you want to be able to display a consistent precision for users.

<?php
function decimal($val, $precision = 0) {
    if ((float)
$val) :
       
$val = round((float) $val, (int) $precision);
        list(
$a, $b) = explode('.', $val);
        if (
strlen($b) < $precision) $b = str_pad($b, $precision, '0', STR_PAD_RIGHT);
        return
$precision ? "$a.$b" : $a;
    else :
// do whatever you want with values that do not have a float
       
return $val;
    endif;
}
?>
info at marc-gutt dot de
27.08.2008 0:55
<?php
function floatvalue($value) {
     return
floatval(preg_replace('#^([-]*[0-9\.,\' ]+?)((\.|,){1}([0-9-]{1,2}))*$#e', "str_replace(array('.', ',', \"'\", ' '), '', '\\1') . '.\\4'", $value));
}
?>

It is much shorter and able to handle those one, too:
xx,-
xx,--
xx'xxx,xx

After using floatvalue() you can go forward with number_format() as usual.
Michiel
30.07.2008 14:21
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:

<?php
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);
           
           
$pregResult = array();
       
           
$commaset = strpos($pString,',');
            if (
$commaset === false) {$commaset = -1;}
       
           
$pointset = strpos($pString,'.');
            if (
$pointset === false) {$pointset = -1;}
       
           
$pregResultA = array();
           
$pregResultB = array();
       
            if (
$pointset < $commaset) {
               
preg_match('#(([-]?[0-9]+(\.[0-9])?)+(,[0-9]+)?)#', $pString, $pregResultA);
            }
           
preg_match('#(([-]?[0-9]+(,[0-9])?)+(\.[0-9]+)?)#', $pString, $pregResultB);
            if ((isset(
$pregResultA[0]) && (!isset($pregResultB[0])
                    ||
strstr($preResultA[0],$pregResultB[0]) == 0
                   
|| !$pointset))) {
               
$numberString = $pregResultA[0];
               
$numberString = str_replace('.','',$numberString);
               
$numberString = str_replace(',','.',$numberString);
            }
            elseif (isset(
$pregResultB[0]) && (!isset($pregResultA[0])
                    ||
strstr($pregResultB[0],$preResultA[0]) == 0
                   
|| !$commaset)) {
               
$numberString = $pregResultB[0];
               
$numberString = str_replace(',','',$numberString);
            }
            else {
                return
false;
            }
           
$result = (float)$numberString;
            return
$result;
}
?>

Comparing of float parsing functions with the following function:

<?php
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"
   
);
   
    echo
"<table>
        <tr>
            <th>String</th>
            <th>floatval()</th>
            <th>getFloat()</th>
            <th>parseFloat()</th>
        </tr>"
;
       
    foreach (
$floatvals as $fval) {
        echo
"<tr>";
        echo
"<td>" . (string) $fval . "</td>";
       
        echo
"<td>" . (float) floatval($fval) . "</td>";
        echo
"<td>" . (float) getFloat($fval) . "</td>";
        echo
"<td>" . (float) parseFloat($fval) . "</td>";
        echo
"</tr>";
    }
    echo
"</table>";
}
?>
steve at opilo dot net
21.07.2008 3:07
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:

<?php $output = floatval(ereg_replace("[^-0-9\.]","",$input)); ?>
leprau at leprau dot de
19.07.2007 18:26
For those of you, who are looking for a function that rips the first,
but longest possible float (or at least integer) from a string,
like 123.45 from the string "Price: 123,45$"

If no useable value is found, the function returns false.

Checks for both comma and dot as decimal-separator,
but does not check for 3 digits between thousands,
so 1,234.5 is as valid as 1,23,4.5 (both will return 1234.5)

12,.3 will return 12
1,000,000 will return 1000.0 !

(if thousands separator is defined,
decimals should be defined too ...
in fact I was too lazy to check for that too)

Here you go, and feel free to optimize the function ;)
<?php
function getFloat($pString) {
    if (
strlen($pString) == 0) {
            return
false;
    }
   
$pregResult = array();

   
$commaset = strpos($pString,',');
    if (
$commaset === false) {$commaset = -1;}

   
$pointset = strpos($pString,'.');
    if (
$pointset === false) {$pointset = -1;}

   
$pregResultA = array();
   
$pregResultB = array();

    if (
$pointset < $commaset) {
       
preg_match('#(([-]?[0-9]+(\.[0-9])?)+(,[0-9]+)?)#', $pString, $pregResultA);
    }
   
preg_match('#(([-]?[0-9]+(,[0-9])?)+(\.[0-9]+)?)#', $pString, $pregResultB);
    if ((isset(
$pregResultA[0]) && (!isset($pregResultB[0])
            ||
strstr($preResultA[0],$pregResultB[0]) == 0
           
|| !$pointset))) {
       
$numberString = $pregResultA[0];
       
$numberString = str_replace('.','',$numberString);
       
$numberString = str_replace(',','.',$numberString);
    }
    elseif (isset(
$pregResultB[0]) && (!isset($pregResultA[0])
            ||
strstr($pregResultB[0],$preResultA[0]) == 0
           
|| !$commaset)) {
       
$numberString = $pregResultB[0];
       
$numberString = str_replace(',','',$numberString);
    }
    else {
        return
false;
    }
   
$result = (float)$numberString;
    return
$result;
}
?>
aa at geb-team dot de
4.09.2006 17:03
@pillepop2003 at yahoo dot de

<?php
float
('-100.00', array('single_dot_as_decimal' => true)); // whoops, returns -10000
?>

use: "/^[0-9-]*[\.]{1}[0-9-]+$/"
instead of: "/^[0-9]*[\.]{1}[0-9-]+$/"

19.04.2005 14:30
you can also use typecasting instead of functions:

(float) $value;
pillepop2003 at yahoo dot de
14.12.2004 11:38
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.

<?php

   
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
               
               
return floatval($str);
            }
            else
            {
               
// No comma exists, so we have to decide, how a single dot shall be treated
               
if(preg_match("/^[0-9]*[\.]{1}[0-9-]+$/", $str) == TRUE && $set['single_dot_as_decimal'] == TRUE)
                {
                   
// Treat single dot as decimal separator
                   
return floatval($str);
                   
                }
                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;
        }
    }

// Examples

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

?>

Big Up.
Philipp
anonymous at start dot be
16.06.2004 4:00
Easier-to-grasp-function for the ',' problem.

<?php
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
?>
vickers at hotpop dot com
27.01.2004 0:45
floatval() does not work with "$35,234.43", as it could not handle the '$' and the ','.  The following takes care of all values, such that only numeric and the decimal sign are input into floatval().  (It probably shows I'm an old 'c' guy)...this function only lightly tested.

<?php
function strtflt($str) {
   
$il = strlen($str);
   
$flt = "";
   
$cstr = "";
   
    for(
$i=0;$i<$il;$i++) {
       
$cstr = substr($str, $i, 1);
        if(
is_numeric($cstr) || $cstr == ".")
           
$flt = $flt.$cstr;
    }
    return
floatval($flt);
}
?>

Richard Vickers
vickers@hotpop.com
Zipi
25.04.2003 11:51
This function converts a string to a float no matter is the decimal separator dot (.) or comma (,). It also converts integers correctly. It takes the digits from the beginning of the string and ignores all other characters.

<?php
function floatval($strValue) {
  
$floatValue = ereg_replace("(^[0-9]*)(\\.|,)([0-9]*)(.*)", "\\1.\\3", $strValue);
   if (!
is_numeric($floatValue)) $floatValue = ereg_replace("(^[0-9]*)(.*)", "\\1", $strValue);
   if (!
is_numeric($floatValue)) $floatValue = 0;
   return
$floatValue;
  }
?>

-Zipi (Finland)
jason at shadonet dot com
8.03.2003 4:07
Instead of using floatval which only appeared in PHP 4.2 you could juse use $variable = (float)$variable

This function doesn't seem to add any functionality that wasn't already there.



PHP Powered Diese Seite bei php.net
The PHP manual text and comments are covered by the Creative Commons Attribution 3.0 License © the PHP Documentation Group - Impressum - mail("TO:Reinhard Neidl",...)