Unknown
Unknown

Reputation: 11

Rounding off to 2 decimal places for wtforms floatfield

I'm looking for a way to limit the floatfield in Flask to 2 decimal places. These are my codes:

from wtforms import Form, StringField, FloatField, validators


class CreateProductForm(Form):
    name = StringField('Product Name', [validators.Length(min=1, max=150), validators.DataRequired()])
    category = StringField('Category', [validators.Length(min=1, max=150), validators.DataRequired()])
    brand = StringField('Brand', [validators.Length(min=1, max=150), validators.DataRequired()])
    price = FloatField('Price ($)', [validators.DataRequired()])

Upvotes: 1

Views: 1170

Answers (1)

Gaurav Shetty
Gaurav Shetty

Reputation: 49

WTForms recommends using DecimalField for most cases as mentioned in the documentation.

There doesn't seem to be a direct way to round off decimal fields in wtforms. The solution mentioned here may help in solving your issue.

You need to create a class that inherits the DecimalField class and create a new Field class that rounds off your decimal values.

Upvotes: 1

Related Questions