PHP-使用NumberFormatter验证小数



我正在开发的应用程序接受来自非英语地区(主要是丹麦语(用户的十进制数字。

验证数字的代码如下所示:

$fmt = new NumberFormatter($locale, NumberFormatter::DECIMAL);
$amount = $fmt->parse($input);
if ($amount === false) {
echo "There has been an error with the number {$input}";
}

这很好,因为它为字符串抛出错误并接受小数。我对NumberFormatter的问题是,例如"12,34,,,,5,34"被接受并格式化为12.34

现在,"12,34,,,,5,34"不是十进制数字,它应该被拒绝。我尝试将其与is_numeric()相结合,但is_numeric()拒绝"12,34,,,,5,34"和12,34。

我的问题是,有没有办法让NumberFormatter拒绝"12,34,,,,5,34",因为这不是数字??

NumberFormatter不用于输入验证。您可以尝试filter_var/filter_input方法:

<?php
setlocale(LC_ALL, 'de_DE');
$options = [
'options' => [
'decimal' => localeconv()['decimal_point'],
],
];
$input = '10,0205,,04';
var_dump(
filter_var($input, FILTER_VALIDATE_FLOAT, $options)
);
# bool(false)
$input = '10,0205';
var_dump(
filter_var($input, FILTER_VALIDATE_FLOAT, $options)
);
# float(10.0205)

希望我能帮助

/Flo

最新更新