Ir al contenido
Odoo Menú
  • Iniciar sesión
  • Pruébalo gratis
  • Aplicaciones
    Finanzas
    • Contabilidad
    • Facturación
    • Gastos
    • Hoja de cálculo (BI)
    • Documentos
    • Firma electrónica
    Ventas
    • CRM
    • Ventas
    • PdV para tiendas
    • PdV para restaurantes
    • Suscripciones
    • Alquiler
    Sitios web
    • Creador de sitios web
    • Comercio electrónico
    • Blog
    • Foro
    • Chat en vivo
    • eLearning
    Cadena de suministro
    • Inventario
    • Manufactura
    • PLM
    • Compras
    • Mantenimiento
    • Calidad
    Recursos humanos
    • Empleados
    • Reclutamiento
    • Vacaciones
    • Evaluaciones
    • Referencias
    • Flotilla
    Marketing
    • Redes sociales
    • Marketing por correo
    • Marketing por SMS
    • Eventos
    • Automatización de marketing
    • Encuestas
    Servicios
    • Proyectos
    • Registro de horas
    • Servicio externo
    • Soporte al cliente
    • Planeación
    • Citas
    Productividad
    • Conversaciones
    • Aprobaciones
    • IoT
    • VoIP
    • Artículos
    • WhatsApp
    Aplicaciones externas Studio de Odoo Plataforma de Odoo en la nube
  • Industrias
    Venta minorista
    • Librería
    • Tienda de ropa
    • Mueblería
    • Tienda de abarrotes
    • Ferretería
    • Juguetería
    Alimentos y hospitalidad
    • Bar y pub
    • Restaurante
    • Comida rápida
    • Casa de huéspedes
    • Distribuidora de bebidas
    • Hotel
    Bienes inmuebles
    • Agencia inmobiliaria
    • Estudio de arquitectura
    • Construcción
    • Gestión de bienes inmuebles
    • Jardinería
    • Asociación de propietarios
    Consultoría
    • Firma contable
    • Partner de Odoo
    • Agencia de marketing
    • Bufete de abogados
    • Adquisición de talentos
    • Auditorías y certificaciones
    Manufactura
    • Textil
    • Metal
    • Muebles
    • Comida
    • Cervecería
    • Regalos corporativos
    Salud y ejercicio
    • Club deportivo
    • Óptica
    • Gimnasio
    • Especialistas en bienestar
    • Farmacia
    • Peluquería
    Trades
    • Personal de mantenimiento
    • Hardware y soporte de TI
    • Sistemas de energía solar
    • Zapateros y fabricantes de calzado
    • Servicios de limpieza
    • Servicios de calefacción, ventilación y aire acondicionado
    Otros
    • Organización sin fines de lucro
    • Agencia para la protección del medio ambiente
    • Alquiler de anuncios publicitarios
    • Fotografía
    • Alquiler de bicicletas
    • Distribuidor de software
    Descubre todas las industrias
  • Odoo Community
    Aprende
    • Tutoriales
    • Documentación
    • Certificaciones
    • Capacitación
    • Blog
    • Podcast
    Fortalece la educación
    • Programa educativo
    • Scale Up! El juego empresarial
    • Visita Odoo
    Obtén el software
    • Descargar
    • Compara ediciones
    • Versiones
    Colabora
    • GitHub
    • Foro
    • Eventos
    • Traducciones
    • Conviértete en partner
    • Servicios para partners
    • Registra tu firma contable
    Obtén servicios
    • Encuentra un partner
    • Encuentra un contador
    • Contacta a un consultor
    • Servicios de implementación
    • Referencias de clientes
    • Soporte
    • Actualizaciones
    GitHub YouTube Twitter LinkedIn Instagram Facebook Spotify
    +1 (650) 691-3277
    Solicita una demostración
  • Precios
  • Ayuda

Odoo is the world's easiest all-in-one management software.
It includes hundreds of business apps:

  • CRM
  • e-Commerce
  • Contabilidad
  • Inventario
  • PoS
  • Proyectos
  • MRP
All apps
Debe estar registrado para interactuar con la comunidad.
Todas las publicaciones Personas Insignias
Etiquetas (Ver todo)
odoo accounting v14 pos v15
Acerca de este foro
Debe estar registrado para interactuar con la comunidad.
Todas las publicaciones Personas Insignias
Etiquetas (Ver todo)
odoo accounting v14 pos v15
Acerca de este foro
Ayuda

Float division by zero

Suscribirse

Reciba una notificación cuando haya actividad en esta publicación

Se marcó esta pregunta
3 Respuestas
4554 Vistas
Avatar
Pete Charalampopoulos

Hi.

I have put a simple division together but when the denominator is 0 then i get the 

float division by zero error

Here in my code: 

i found some examples and tried them but nothing works.


Any help would be appreciated

 

0
Avatar
Descartar
Avatar
Cybrosys Techno Solutions Pvt.Ltd
Mejor respuesta

Hi,

It seems like you want to avoid the "float division by zero" error when record.price_subtotal is zero. You can add a check to handle this situation. Here's an example of how you can modify your code to handle division by zero:

for record in self:
if record.price_subtotal != 0:
    record['x_studio_gross_margin'] = record.x_studio_gross_profit / record.price_subtotal
else:
    # Handle the division by zero case, for example, set x_studio_gross_margin to a default value
    record['x_studio_gross_margin'] = 0.0  # You can choose any default value here


This modification checks if record.price_subtotal is not equal to zero before performing the division. If it's zero, it sets x_studio_gross_margin to a default value (in this case, 0.0). You can adjust the default value according to your requirements.

or you can try


for record in self:
try:
    record['x_studio_gross_margin'] = record.x_studio_gross_profit / record.price_subtotal
except ZeroDivisionError:
    # Handle the division by zero case, for example, set x_studio_gross_margin to a default value
    record['x_studio_gross_margin'] = 0.0  # You can choose any default value here


Hope it helps

0
Avatar
Descartar
Pete Charalampopoulos
Autor

Thank you, Both work

Avatar
Jainesh Shah(Aktiv Software)
Mejor respuesta

Hello Pete Charalampopoulos,


To resolve this error you just need to add a condition to check price_subtotal as follow and if the price_subtotal is zero then x_studio_gross_margin should also be zero.


for record in self:

    record['x_studio_gross_margin'] = (record.x_studio_gross_profit / record.price_subtotal) if record.price_subtotal else 0

I hope this will help you. 

Thanks & Regards,
Email:   odoo@aktivsoftware.com      

Skype: kalpeshmaheshwari

0
Avatar
Descartar
Avatar
Charles Edouard TOUTAIN
Mejor respuesta

To handle the "float division by zero" error in Python, you can use a try-except block to catch the `ZeroDivisionError` exception. This way, you can manage the situation when the denominator is zero without having your program crash.


Here's an example of how you might modify your code to handle this:


```python

try:

    # Your division code here

    # Example: result = numerator / denominator

except ZeroDivisionError:

    # Handle the division by zero error

    # or

    # result = None

```


In this example, replace the comment `# Your division code here` with your actual division operation. If the denominator in your division is zero, the `ZeroDivisionError` will be raised, and the code within the `except` block will execute. This allows you to handle the error gracefully, such as by printing an error message or setting the result to a default value like `None`.

0
Avatar
Descartar
Pete Charalampopoulos
Autor

Hi Charles

i have added your recommendation on the bottom of my code

and i get the following error:
except ZeroDivisionError:
IndentationError: unexpected indent

here is the code:

for record in self:
record['x_studio_gross_margin'] = record.x_studio_gross_profit / record.price_subtotal
except ZeroDivisionError:
result = None

¿Le interesa esta conversación? ¡Participe en ella!

Cree una cuenta para poder utilizar funciones exclusivas e interactuar con la comunidad.

Registrarse
Comunidad
  • Tutoriales
  • Documentación
  • Foro
Código abierto
  • Descargar
  • GitHub
  • Runbot
  • Traducciones
Servicios
  • Alojamiento en Odoo.sh
  • Soporte
  • Actualizaciones del software
  • Desarrollos personalizados
  • Educación
  • Encuentra un contador
  • Encuentra un partner
  • Conviértete en partner
Sobre nosotros
  • Nuestra empresa
  • Activos de marca
  • Contáctanos
  • Empleos
  • Eventos
  • Podcast
  • Blog
  • Clientes
  • Legal • Privacidad
  • Seguridad
الْعَرَبيّة Català 简体中文 繁體中文 (台灣) Čeština Dansk Nederlands English Suomi Français Deutsch हिंदी Bahasa Indonesia Italiano 日本語 한국어 (KR) Lietuvių kalba Język polski Português (BR) română русский язык Slovenský jazyk slovenščina Español (América Latina) Español ภาษาไทย Türkçe українська Tiếng Việt

Odoo es un conjunto de aplicaciones de código abierto que cubren todas las necesidades de tu empresa: CRM, comercio electrónico, contabilidad, inventario, punto de venta, gestión de proyectos, etc.

La propuesta única de valor de Odoo es ser muy fácil de usar y estar totalmente integrado.

Sitio web hecho con

Odoo Experience on YouTube

1. Use the live chat to ask your questions.
2. The operator answers within a few minutes.

Live support on Youtube
Watch now