note 114486 added to function.floatval

From: Date: Wed, 26 Feb 2014 09:25:22 +0000
Subject: note 114486 added to function.floatval
Groups: php.notes 
Request: Send a blank email to php-notes+get-198728@lists.php.net to get a copy of this message
This function takes the last comma or dot (if any) to make a clean float, ignoring thousand separator, currency or any other letter : function tofloat($num) { $dotPos = strrpos($num, '.'); $commaPos = strrpos($num, ','); $sep = (($dotPos > $commaPos) && $dotPos) ? $dotPos : ((($commaPos > $dotPos) && $commaPos) ? $commaPos : false); 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) Demo : http://codepad.org/NW4e9hQH ---- Server IP: 195.221.21.36 Probable Submitter: 78.115.181.204 ---- Manual Page -- http://php.net/manual/en/function.floatval.php Edit -- https://master.php.net/note/edit/114486 Del: integrated -- https://master.php.net/note/delete/114486/integrated Del: useless -- https://master.php.net/note/delete/114486/useless Del: bad code -- https://master.php.net/note/delete/114486/bad+code Del: spam -- https://master.php.net/note/delete/114486/spam Del: non-english -- https://master.php.net/note/delete/114486/non-english Del: in docs -- https://master.php.net/note/delete/114486/in+docs Del: other reasons-- https://master.php.net/note/delete/114486 Reject -- https://master.php.net/note/reject/114486 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#198728) next »