如何将php变量字符串转换为int


how to convert php variable string to int

如何将此字符串变量转换为整数

2, 990.00

我想输出这个

2990.00

如果我加上两个像这个的数字

$num1 = '2, 990.00'; <br>
$num2 = '7, 990.00'; <br>
<br><br>
$ans = $num1 + $num2;<br>
echo $ans;

答案是9

您可以使用preg_replace("/[^0-9.]/", "", $subject)来消除非数字字符。

intval()无法使用您所拥有的字符串,因为存在逗号。您可以使用str_replace()删除逗号,然后调用intval(),如下所示:

echo intval(str_replace(',', '', $myVal));

如果你想保留小数点后:

echo floatval(str_replace(',', '', $myVal));

$num1 = '2, 990.00';
$rep = array(',',' ');
$replace = array('','');
echo str_replace($rep,$replace,$num1);