1. 什么是浮点数? #

pi = 3.14
price = 19.99
ratio = 7 / 3              # 2.3333333333333335

print(float("3.14"))       # 从字符串解析
print(type(pi))            # <class 'float'>

2. 精度问题(重要) #

print(0.1 + 0.2)           # 0.30000000000000004
print(0.1 + 0.2 == 0.3)    # False
import math

print(math.isclose(0.1 + 0.2, 0.3))   # True

3. 显示与四舍五入 #

price = 19.9876

print(round(price, 2))         # 20.0(注意:round(2.5) 为 2,银行家舍入)
print(f"¥{price:.2f}")          # ¥19.99(展示金额常用)

4. 金额与精确计算:Decimal #

from decimal import Decimal

a = Decimal("0.1")
b = Decimal("0.2")
print(a + b)                   # 0.3(精确)

# 用字符串初始化,不要用 Decimal(0.1)
total = Decimal("19.99") * Decimal("3")
print(total)                   # 59.97(精确)

5. 项目开发要点 #