Checking Results With Number.isFinite()

The invoices are in order, and the order numbers remain exact. The bookkeeper’s script has one more report to port. It lists the price each café paid per kilo in October, followed by the month’s average price per kilo. The roastery can use the report to check that each café was charged its listed price. This month, the list includes Corner Mill, the café that took a tasting sample in September and ordered nothing in October.

A café with no kilos makes the division meaningless. Python refuses to do it, while JavaScript hands back an answer and keeps going. In this lesson, you’ll see where those answers come from and how to stop them before they reach a report.

The Python script divides each café’s amount by its kilos and formats the result as euros:

Language: Python
from decimal import Decimal

cafe_totals = [
    {"name": "Larder Lane", "kg": 36.0, "amount": Decimal("666.00")},
    {"name": "Bluebell Café", "kg": 9.0, "amount": Decimal("172.80")},
    {"name": "Northside Kitchen", "kg": 27.0, "amount": Decimal("464.40")},
    {"name": "Corner Mill", "kg": 0.0, "amount": Decimal("0.00")},
]

for cafe in cafe_totals:
    price = float(cafe["amount"]) / cafe["kg"]
    print(f"{cafe['name']}: €{price:.2f} per kg")

Python prints the three prices, then stops at Corner Mill with ZeroDivisionError: division by zero. The traceback is annoying, but it also guarantees that this division never puts a nonsense price on a report line.

The port keeps grams and cents as whole numbers and formats euros with the invoices’ Intl.NumberFormat currency formatter:

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Become a Member to join the conversation.