gpt4 book ai didi

python - WTForms 中的小数字段舍入

转载 作者:太空狗 更新时间:2023-10-30 01:21:57 25 4
gpt4 key购买 nike

我有一个包含价格小数字段的表单,如下所示:

from flask.ext.wtf import Form
import wtforms
from wtforms.validators import DataRequired
from decimal import ROUND_HALF_UP

class AddListingBase(Form):
title = wtforms.StringField(validators=[DataRequired()])
details = wtforms.TextAreaField(validators=[DataRequired()])
price = wtforms.DecimalField(places=2, rounding=ROUND_HALF_UP, validators=[DataRequired()])

当我提交表单时,十进制值应该四舍五入到小数点后两位,但这种情况从未发生过。我总是得到指定的值(例如 99.853 是 99.853,而不是应该的 99.85)。

最佳答案

正如@mueslo 正确推断的那样,这是因为默认的 DecimalField 实现不会对其接收的表单数据 进行四舍五入。它只对初始数据进行四舍五入(如默认值,或模型/保存的数据)。

我们可以通过修改后的 DecimalField 实现轻松更改此行为,其中我们覆盖了 process_formdata 方法。有点像这样:

from wtforms import DecimalField


class BetterDecimalField(DecimalField):
"""
Very similar to WTForms DecimalField, except with the option of rounding
the data always.
"""
def __init__(self, label=None, validators=None, places=2, rounding=None,
round_always=False, **kwargs):
super(BetterDecimalField, self).__init__(
label=label, validators=validators, places=places, rounding=
rounding, **kwargs)
self.round_always = round_always

def process_formdata(self, valuelist):
if valuelist:
try:
self.data = decimal.Decimal(valuelist[0])
if self.round_always and hasattr(self.data, 'quantize'):
exp = decimal.Decimal('.1') ** self.places
if self.rounding is None:
quantized = self.data.quantize(exp)
else:
quantized = self.data.quantize(
exp, rounding=self.rounding)
self.data = quantized
except (decimal.InvalidOperation, ValueError):
self.data = None
raise ValueError(self.gettext('Not a valid decimal value'))

示例用法:

rounding_field = BetterDecimalField(round_always=True)

Gist

关于python - WTForms 中的小数字段舍入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27781926/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com