[ create a new paste ] login | about

Link: http://codepad.org/NW4e9hQH    [ raw code | output | fork | 3 comments ]

PHP, pasted on Feb 26:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?php
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));
$otherNum = '126,564,789.33 m²';
var_dump(tofloat($otherNum));


Output:
1
2
float(1999.369)
float(126564789.33)


Create a new paste based on this one


Comments:
posted by codepad.org@stanislaveckert.de on Oct 12
This code has a small bug: It does not handle negative values. The RegEx should be "/[^\\-0-9]/", not "/[^0-9]/" in all three cases.
reply
posted by tomkyle+codepad@posteo.de on Dec 5
Makes sense. Forked it: http://codepad.org/xtWvkKiw
reply
posted by gaabora on Oct 7
also it breaks integer values with thousand separators like 126,564,789 >> 126564.789
reply