How to compare two float numbers in Odoo

If you need to compare two float numbers in Odoo you should use the method float_compare. This method allows you to have more accurate results in your calculation. Except for the values that need to be compared this method as arguments receives precision_digits and precision_rounding. You need to choose only one of these arguments because the precision must be by digits or rounding.

For example, if you want to compare 8.945 and 8,946 with precision_digits 2 the return result will be 0 that means both values are same. In a case when precision_digits is 3 the return value will be -1 that means the second value is bigger than the first.

# Odoo 9
from openerp.tools import float_compare

# Odoo 10
from odoo.tools import float_compare

>>> float_compare(8.945, 8.946, precision_digits=2)
>>> 0

>>> float_compare(8.945, 8.946, precision_digits=3)
>>> -1

>>> float_compare(8.946, 8.945, precision_digits=3)
>>> 1

You can find more how this method works in the Github Odoo repository

Share the knowledge!

Leave a Reply

Your email address will not be published. Required fields are marked *