浮点转换不起作用

时间:2016-09-04 02:15:45

标签: php numbers

我有这个功能,我希望它能很好地将字符串转换为浮点数

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但我需要该函数来摆脱字母空格等。

1 个答案:

答案 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);
}