我正在使用Odoov8并发现了一个有趣的行为。
当我用数字声明浮点数时:
pension_unit_rate = fields.Float(digits=(16,4))
并把
<field name="pension_unit_rate" widget="progressbar"/>
在其视图定义中,将数据 0.06 输入到记录中并保存,数据在 PostgreSQL 数据库中正确存储为 0.06。
但是当我单击"编辑"按钮时,从数据库读回的数据是0.0600000000000000005。
我使用 pgAdmin 和简单的代码检查验证了数据库中的数据是否正确 (0.06):
instance.web.form.FieldProgressBar = instance.web.form.AbstractField.extend({
template: 'FieldProgressBar',
render_value: function() {
this.$el.progressbar({
value: this.get('value') || 0,
disabled: this.get("effective_readonly")
});
**console.log(this.get('value'))**
var formatted_value = instance.web.format_value(this.get('value') || 0, { type : 'float' });
this.$('span').html(formatted_value + '%');
}});
似乎存储在"值"中的数据是 0.060000000000000005,这与数据库中存在的数据不一致。
这是由使用数字选项时的数字数据类型引起的吗?是否有解决方法或修复程序?
提前感谢~
找到了答案。
问题出在 fields.py 中 Float 字段定义中的旧版本convert_to_cache函数。更新代码解决了问题。
def convert_to_cache(self, value, record, validate=True):
# apply rounding here, otherwise value in cache may be wrong!
value = float(value or 0.0)
if not validate:
return value
digits = self.digits
return float_round(value, precision_digits=digits[1]) if digits else value