Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accepting either '.' or ',' as decimal separators when using FILTER_VALIDATE_FLOAT?

Tags:

php

I'm using the PHP filter_input function to parse an HTML form input. One of the input fields represents an amount of money. I expect that I will have some users using commas and some using dots as decimal separator. The FILTER_VALIDATE_FLOAT filter has a decimal option but I haven't figured out a clean way of accepting both characters as decimal separator.

Currently my code looks like the following line, but this doesn't accept amounts like 123.45.

$money = filter_input(INPUT_POST, 'money', FILTER_VALIDATE_FLOAT, array('options' => array('decimal' => ',')));

Is there any standard / clean way of accepting several types of decimal separator, without having to writing a custom parsing function?

like image 203
Kevin Salvesen Avatar asked Aug 25 '26 08:08

Kevin Salvesen


1 Answers

I rewrote my code using filter_var instead of filter_input and used hd's str_replace trick. The end result looks something like:

$temp_money = str_replace(".", ",", $_POST['money']);
$money = filter_var($temp_money, FILTER_VALIDATE_FLOAT, array('options' => array('decimal' => ',')));

If $_POST['money'] is null then $money will also be null, which is the same behavior as filter_input, so the rest of my validation code did not have to be changed.

like image 165
Kevin Salvesen Avatar answered Aug 28 '26 00:08

Kevin Salvesen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!