【发布时间】:2020-01-01 17:54:48
【问题描述】:
我想知道如何能够将任何字符串转换为浮点数,并且可以切换千位分隔符和十进制指针。这在处理欧洲和美国格式时非常有用。例如。 '2,192,520.12' 或 '2.192.520,12'
【问题讨论】:
标签: php string floating-point type-conversion
我想知道如何能够将任何字符串转换为浮点数,并且可以切换千位分隔符和十进制指针。这在处理欧洲和美国格式时非常有用。例如。 '2,192,520.12' 或 '2.192.520,12'
【问题讨论】:
标签: php string floating-point type-conversion
您可以通过正则表达式删除除最后一个以外的所有分隔符
[,.](?=.+[,.])
所以你得到2192520.12 或2192520,12。并将逗号替换为点。这将是正确的数字格式
$re = '/[,.](?=.+[,.])/m';
$subst = '';
$result = preg_replace($re, $subst, $str);
$result = str_replace(',', '.', $result); // 2192520.12
如果您想将数字处理为1,000,那么我们应该设置该小数部分最多可以包含 2 位数字。正则表达式将是
[,.](?=.+[,.]|\d{3})
否则你无法区分 1.027(一个带小数)和 1027
【讨论】:
我想出了什么:
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, [ '.' => '', ',' => '.' ] );
}
请随意扩展此方法,我很想看看我们能想出什么。
【讨论】: