我有这个功能,我希望它能很好地将字符串转换为浮点数:
function getFloat($value) {
$cleanString = preg_replace('/([^0-9\.,])/i', '', $value);
$onlyNumbersString = preg_replace('/([^0-9])/i', '', $value);
$separatorsCountToBeErased = strlen($cleanString) - strlen($onlyNumbersString) - 1;
$stringWithCommaOrDot = preg_replace('/([,\.])/', '', $cleanString, $separatorsCountToBeErased);
$removedThousendSeparator = preg_replace('/(\.|,)(?=[0-9]{3,}$)/', '', $stringWithCommaOrDot);
return (float) str_replace(',', '.', $removedThousendSeparator);
}
然而:
$str = '449.0000';
echo getFloat($str);
// => 4490000
所以我试过了:
$str = '449.0000';
echo filter_var($str, FILTER_SANITIZE_NUMBER_FLOAT );
// => 4490000
为什么他们都将449.0000
转换为449000
?
这里唯一可行的是(float) $str
,它按预期返回449
但我需要该函数来摆脱字母空格等。
答案 0 :(得分:1)
我喜欢使用FILTER_VALIDATE_FLOAT
<?php
$str = '449.0000';
$filter = filter_var($str,FILTER_VALIDATE_FLOAT);
var_dump($filter);
if ($filter !== false) {
$float = floatval($filter);
var_dump($float);
}