How to Implement float_is_zero and float_compare  in Odoo?

Why Use Them?

In Odoo, financial and quantity calculations often involve floating-point numbers, which can suffer from precision issues (e.g., 0.00000001 ≠ 0). To ensure accurate comparisons, Odoo provides utility functions:

  • float_is_zero(): Check if a float is effectively zero.
  • float_compare(): Compare two float values considering precision.
These are defined in Odoo’s utility module: from odoo.tools.float_utils import float_is_zero, float_compare

1. float_is_zero())

Purpose:

Safely determine whether a float value is equal to zero, considering the precision of the unit of measure (UoM) or currency.

✅ Syntax
float_is_zero(value, precision_digits)
  • value: The float to compare
  • precision_digits: The number of decimal digits to consider (e.g., 2 for currency, 6 for quantities)

📌 Realistic Example

Check if a product quantity is effectively zero:

from odoo.tools.float_utils import float_is_zero

if float_is_zero(line.product_uom_qty, precision_digits=6):

    raise UserError(“Quantity cannot be zero.”)

Useful in stock movements or manufacturing where precision matters.

2. float_compare()
Purpose:

Compare two float values with a defined precision.

✅ Syntax

float_compare(value1, value2, precision_digits)

Returns 0 if equal, -1 if value1 < value2, 1 if value1 > value2

📌 Realistic Example

from odoo.tools.float_utils import float_compare

if float_compare(order.amount_total, 1000.0, precision_digits=2) > 0:

    order.message_post(body=“High-value order (above 1000).”)

Can be used to:

  • Validate minimum order amounts
  • Trigger logic on price or quantity thresholds

✅ Summary Table

Function Purpose Returns Use Case
float_is_zero() Check if float ≈ 0 True / False Zero-check in quantities, balances
float_compare() Compare two floats safely 0, -1, or 1 Price thresholds, conditional logic