liveBook · Manning

Floating-point arithmetic

As explained in Python How-To

A floating-point number is a numeric representation for values that may contain a fractional component and use finite precision.

Need to compare a temperature entered at the console? Input arrives as a string, so convert it with float() before comparing it with numbers. The result is a Python float even when the string contains an integer, as in float("-2") → -2.0. section 2.2.2

Compare a temperature and format the result

temperature = float(input("Temperature in Celsius: ")) if temperature < 10: label = "cold" elif temperature <= 25: label = "cool" else: label = "hot" print(f"You entered {temperature:.1f} degrees. It's {label}!") For input 15.75, the output is: You entered 15.8 degrees. It's cool! section 2.2.5

An f-string format specifier controls how a float appears in text: .2f displays two digits after the decimal point, .2e uses scientific notation, and .2% displays a percentage with two decimal places. Choose the form that makes the value easiest to read. section 2.1.4

decimal_number = 1.23456

print(f"Two digits: {decimal_number:.2f}")
# output: Two digits: 1.23

print(f"Four digits: {decimal_number:.4f}")
# output: Four digits: 1.2346

Compare .2f and .4f on the same value to see how the requested number of displayed decimal places changes the output. section 2.1.4

Conversion can fail: float("3.5a") raises ValueError. Use try...except... when input may be invalid. When exchanging data through JSON, remember that JSON has one number category, while Python represents corresponding values with int or float. section 2.2.2 section 9.3.2

How Python How-To covers it

How deep it goes
Works through casting and display formats, but stops short of floating-point representation or arithmetic internals.
Examples
Uses a Celsius-temperature exercise, decimal-place output, invalid numeric strings, and JSON numbers.
What it assumes
Assumes basic Python input, strings, and comparisons while introducing float() casting and decimal format specifiers through examples.
What you can do after
Apply it via Python's float() and f-strings to compare numeric input and display chosen decimal places.
How it connects
Connects floats to string casting, exception handling, f-string format specifiers, and JSON number mapping.

Also explained in

Compare how 20 books explain floating-point arithmetic →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python How-To. The section links point to the parts of the book it draws on.