liveBook · Manning

Decimal

As explained in Python Workout: 50 ten-minute exercises

Decimal is a Python numeric class that provides decimal floating-point arithmetic with explicitly represented base-ten values.

Decimal provides decimal floating-point arithmetic for situations where ordinary floats are potentially inaccurate, especially calculations involving money. section 1.16 section 8.2

Adding user-entered decimals

Convert the input strings directly to Decimal instances, add them, and preserve the expected result when users enter values such as 0.1 and 0.2. Keep values as Decimal during arithmetic and convert to float only at the last possible moment. section 1.16 section 8.2

from decimal import Decimal

rates = {
   'Chico': Decimal('0.5'),
   'Groucho': Decimal('0.7'),
   'Harpo': Decimal('0.5'),
   'Zeppo': Decimal('0.4')
}

def time_percentage(hour):
   return hour / Decimal('24.0')

def calculate_tax(amount, state, hour):
   return float(amount + (amount * rates[state] * time_percentage(hour)))

A tax calculation keeps rates and time percentages as Decimal values, then converts the final result to float. section 8.2

How Python Workout: 50 ten-minute exercises covers it

How deep it goes
Demonstrates construction from strings, arithmetic, and conversion to float at the final boundary.
Examples
Uses 0.1 plus 0.2, user-entered decimal strings, and a progressively timed taxation calculation.
What it assumes
Builds on awareness that binary floating-point values can be inaccurate and contrasts Decimal with floats and integers.
What you can do after
Apply it via Python's Decimal class to perform accurate arithmetic and delay conversion to float.
How it connects
Connects Decimal with floating-point arithmetic, integers, modules, and exception-based input validation.

Also explained in

Compare how 5 books explain Decimal →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python Workout: 50 ten-minute exercises. The section links point to the parts of the book it draws on.