Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
463 views
in Technique[技术] by (71.8m points)

python - 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()])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...