Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to accept both dot and comma as a decimal separator with WTForms?

I'm using WTForms to display and validate form input. I use a DecimalField for a money amount input, which works fine when inserting a value with a dot as a decimal separator. Since this website will be used in continental Europe however, I also want to allow a comma as a decimal separator. This means that both "2.5" and "2,5" should result in a value meaning "two and a half".

When I input a value with a comma, I get an error saying 'Not a valid decimal value'. How can I accept both dots and commas as decimal separators with WTForms?


I know I can use Babel to use locale-based number formatting, but I don't want that. I specifically want to accept both a dot and a comma as separator values.

like image 880
kramer65 Avatar asked Jan 20 '15 23:01

kramer65


People also ask

How do you change a decimal separator to a dot?

Click File > Options. On the Advanced tab, under Editing options, clear the Use system separators check box. Type new separators in the Decimal separator and Thousands separator boxes. Tip: When you want to use the system separators again, select the Use system separators check box.

How do you change a period to a decimal with a comma?

Click File | Options. In the pane on the left, click User Interface. In the pane on the right, scroll to the bottom and set the Decimal separator to Period (or Comma). Click OK and the decimal separators will be converted throughout the program.

What is the correct decimal separator?

Both a comma and a period (or full-stop) are generally accepted decimal separators for international use.

What is an example of decimal separator?

Decimal point and decimal comma are also common names for the decimal separator. For example, 9.5 means nine and one half in English speaking countries, while in many European countries, the same number might be written as 9,5.


1 Answers

You can subclass DecimalField and replace commas with periods before the data is processed:

class FlexibleDecimalField(fields.DecimalField):

    def process_formdata(self, valuelist):
        if valuelist:
            valuelist[0] = valuelist[0].replace(",", ".")
        return super(FlexibleDecimalField, self).process_formdata(valuelist)
like image 89
Daniel Robinson Avatar answered Sep 27 '22 16:09

Daniel Robinson