note 116574 deleted from function.floatval by salathe
| From: | salathe@php.net | Date: | Fri, 06 Feb 2015 13:10:34 +0000 |
| Subject: | note 116574 deleted from function.floatval by salathe | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-201619@lists.php.net to get a copy of this message | ||
Note Submitter: troudi dot zied at hotmail dot fr
----
Thinks to Brewal Renault.
To have a good result with float values which start by comma or dot, i propose to add small code to
function tofloat noted in http://php.net/manual/fr/function.floatval.php#114486
<?php
function tofloat($sNum)
{
$iDotPos = strrpos($sNum, '.');
$iCommaPos = strrpos($sNum, ',');
$iSep = (($iDotPos > $iCommaPos) && (false !== $iDotPos)) ? $iDotPos :
((($iCommaPos > $iDotPos) && (false !== $iCommaPos)) ? $iCommaPos : false);
if (!$iSep)
{
if (0 === $iDotPos || 0 === $iCommaPos)
{
$sVal = '.' . preg_replace("/[^0-9]/", "", $sNum);
}
return floatval($sVal);
}
return floatval(
preg_replace("/[^0-9]/", "", substr($sNum, 0, $iSep)) . '.' .
preg_replace("/[^0-9]/", "", substr($sNum, $iSep + 1, strlen($sNum)))
);
}
$num = '1.999,369â¬';
var_dump(tofloat($num)); // float(1999.369)
$otherNum = '126,564,789.33 m²';
var_dump(tofloat($otherNum)); // float(126564789.33)
$sOtherNum1 = ',050';
var_dump(tofloat($sOtherNum1 )); // float(0.05)
Demo : http://codepad.org/hytRLaDc