note 76640 deleted from function.floatval by bjori
| From: | bjori@php.net | Date: | Tue, 24 Jul 2007 11:09:55 +0000 |
| Subject: | note 76640 deleted from function.floatval by bjori | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-128863@lists.php.net to get a copy of this message | ||
Note Submitter: freddy at ff dot net
Reason: bad code
----
leprau at leprau dot de contained some spelling errors, here's an optimized version:
[php]
function atof($sFloat) {
if(strlen($sFloat)==0) return 0;
if(is_numeric($sFloat)) return (float)$sFloat;
if((int)strpos($sFloat,'.')<(int)strpos($sFloat,','))
preg_match('#(([-]?[0-9]+(\.[0-9])?)+(,[0-9]+)?)#',
$sFloat,$afDotFor1k);
else
preg_match('#(([-]?[0-9]+(,[0-9])?)+(\.[0-9]+)?)#',
$sFloat,$afCommaFor1k);
if(isset($afDotFor1k[0]))
return (float)str_replace(',','.',
str_replace('.','',$afDotFor1k[0]));
elseif(isset($afCommaFor1k[0]))
return str_replace(',','',$afCommaFor1k[0]);
else return 0;
}
[/php]
Output would become:
1,234=1.234
1.234=1.234
1.234,56=1234.56
1,234.56=1234.56
EUR 1,234.56=1234.56
EUR 1.234,56=1234.56
1234=1234
EUR -1,234.56=-1234.56
Note that in the case of 1,234 and 1.234 its impossible to know which format is used (English or on
case of my country; Dutch). You could fetch this from the locale, but in my case I couldn't,
since the input data comes from a plain text datasource.