Odoo amount_to_text函数4位小数异常及总计精准处理咨询
解决Odoo amount_to_text函数4位小数金额解析错误问题
针对你遇到的4位小数金额(如0.0640)导致amount_to_text将20.38错误解析为“TWENTY DOLLARS AND THREE THOUSAND EIGHT HUNDRED CENTS”的问题,以下是两种不影响数据库原始价格精度的解决方案:
方案一:调用函数前手动四舍五入金额
仅在需要转换为文本的场景下临时处理小数位数,无需修改核心代码:
- QWeb报表中调用:
<span t-esc="amount_to_text(round(o.total_amount, 2), currency_obj=o.currency_id)"/> - Python代码中调用:
rounded_amount = round(total_amount, 2) amount_text = amount_to_text(rounded_amount, currency_obj=currency_record)
该方法仅作用于金额转文本的环节,数据库中存储的原始4位小数价格完全不受影响。
方案二:重写amount_to_text函数自动适配
通过自定义模块继承并修改原函数,让所有调用场景自动处理小数位数:
- 继承
ir.qweb.field.amount_to_text(适用于QWeb报表的字段渲染):from odoo import models, api class AmountToTextOverride(models.AbstractModel): _inherit = 'ir.qweb.field.amount_to_text' @api.model def value_to_html(self, value, options): # 先将金额四舍五入到两位小数 rounded_value = round(value, 2) return super().value_to_html(rounded_value, options) - 继承
account.amount_to_text(适用于通用的金额转文本函数调用):from odoo import models class AccountAmountToText(models.Model): _inherit = 'account.amount_to_text' def amount_to_text(self, amount, currency): rounded_amount = round(amount, 2) return super().amount_to_text(rounded_amount, currency)
部署该自定义模块后,所有调用amount_to_text的地方都会自动处理小数位数,且不会改变数据库中的原始价格数据。
为什么全局rounding precision设置不可取
全局设置rounding precision为0.01会强制所有价格计算、存储环节都使用两位小数,导致数据库中原始的4位小数价格被永久修改,而上述两种方案仅在金额转文本的临时环节处理小数,完全规避了这个问题。
内容的提问来源于stack exchange,提问作者Sergey Pak
相关产品推荐
相关产品推荐

