在PHP中将带有十进制指针和千位分隔符的字符串转换为浮点

在PHP中将带有十进制指针和千位分隔符的字符串转换为浮点,php,string,floating-point,type-conversion,Php,String,Floating Point,Type Conversion,我想知道如何将任何字符串转换成一个浮点数,并且可以切换上千个分隔符和十进制指针。这在处理欧洲和美国格式时非常有用。例如“2192520.12”或“2.192.520,12”我想到了什么: function makeFloat( $numberString ) { $commaPos = strrpos( $numberString, ',' ); $dotPos = strrpos( $numberString, '.' ); if ( $commaPos === fa

我想知道如何将任何字符串转换成一个浮点数,并且可以切换上千个分隔符和十进制指针。这在处理欧洲和美国格式时非常有用。例如“2192520.12”或“2.192.520,12”

我想到了什么:

function makeFloat( $numberString ) {
    $commaPos = strrpos( $numberString, ',' );
    $dotPos = strrpos( $numberString, '.' );

    if ( $commaPos === false && $dotPos === false ) {
        // string does not contain comma or a dot
        return (float) $numberString;
    }

    if ( $commaPos === false ) {
        // string does not contain a comma, it does contain a dot
        if ( strpos( $numberString, '.' ) === $dotPos ) { // strpos vs strrpos
            // string contains a single dot, assume the dot is the decimal pointer
            return (float) $numberString;
            // if the string is 1.000 this will cast to 1
            // we do not know if this is a thousand separator
        }
        // string contains multiple dots, assume the dots are thousand separators 
        // (again, string does not contains commas)
        return (float) str_replace( '.', '', $numberString );
    }
    // string contains a comma

    if ( $dotPos === false ) {
        // string does not contain a dot, it does contain a comma
        if ( strpos( $numberString, ',' ) === $commaPos ) { // strpos vs strrpos
            // string contains a single comma, assume the comma is the decimal pointer
            return (float) str_replace( ',', '.', $numberString );
            // if the string is 1,000 this will cast to 1
            // we do not know if this is a thousand separator
        }
        // string contains multiple commas, assume the commas are thousand separators
        return (float) str_replace( ',', '', $numberString );
    }
    // string contains both a comma and a dot

    return $dotPos > $commaPos ?
        // the dot is the decimal pointer
        (float) str_replace( ',', '', $numberString ) :
        // the comma is the decimal pointer
        (float) strtr( $numberString, [ '.' => '', ',' => '.' ] );
}

请随意扩展此方法,我很想看看我们能想出什么。

您可以删除所有分隔符,但最后一个由正则表达式删除

[,.](?=.+[,.])
所以你得到2192520.12或2192520.12。并将逗号替换为点。它将是正确的数字格式

$re = '/[,.](?=.+[,.])/m';
$subst = '';
$result = preg_replace($re, $subst, $str);
$result = str_replace(',', '.', $result);  // 2192520.12
如果您想将数字处理为1000,那么我们应该设置小数部分最多可以包含2位数字。而正则表达式将是

[,.](?=.+[,.]|\d{3})
否则你就不能区分1.027和1027


1000和1.000是否存在同样的问题,因为如果将一个只有1个分隔符的非浮点数传递给1000,它会变得非常脆弱。@NigelRen您将如何解决这个问题?这是一个非常干净的解决方案!