How do I convert output of number_format back to numbers in PHP?

Solution 1:

You could remove any character that is not a digit or a decimal point and parse that with floatval:

$number = 1200.00;
$parsed = floatval(preg_replace('/[^\d.]/', '', number_format($number)));
var_dump($number === $parsed);  // bool(true)

And if the number has not . as decimal point:

function parse_number($number, $dec_point=null) {
    if (empty($dec_point)) {
        $locale = localeconv();
        $dec_point = $locale['decimal_point'];
    }
    return floatval(str_replace($dec_point, '.', preg_replace('/[^\d'.preg_quote($dec_point).']/', '', $number)));
}

Solution 2:

If you're using 5.3 or higher (thanks ircmaxell), use numfmt_parse.

Solution 3:

use ; Sanitize filters

$number1= '$ 1,989.34';

    $number2 = filter_var($number, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);//1989.34
    $number2 = filter_var($number, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_THOUSAND);//1,98934

Solution 4:

You can use filter_var. e.g.

$num = '1,200,998';
$real_integer = filter_var($num, FILTER_SANITIZE_NUMBER_INT);
echo $real_integer;

will output:

1200998