PHP can\'t recognize 1,200.00
(generated by number_format
) but only 1200.00
,
What\'s the general solution for this problem?
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
In this case you can, use PHP round
method like: round (12.000000, 2);
You could do $num = (float) str_replace(',', '', $num);
Basically, just get rid of the commas, and then cast it as a numeric type (float or int).
I use the following code:
function remove_non_numerics($str)
{
$temp = trim($str);
$result = "";
$pattern = '/[^0-9]*/';
$result = preg_replace($pattern, '', $temp);
return $result;
}
The better way is to use the options in number_format
function itself. The format is
number_format ( float $number , int $decimals = 0 , string $dec_point = '.' , string $thousands_sep = ',' )
I.e. if you don't need the ','
in the formatted string make, it is like
$num=23.33333
echo number_format($num,2,'.','');
If you need that as float then typecast the same to float
$floatnum= (float) number_format($num,2,'.','');
use "[^0-9.]+" regex.
$formattedVal = '$9,99,999.99';
$unformattedVal = (float)preg_replace("/[^0-9.]+/", "", $formattedVal);
var_dump($unformattedVal);
worked for me.