Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Hàm float() trong Python: Chuyển đổi sang số thực

Hàm float() chuyển đổi số hoặc chuỗi chứa số thành kiểu dữ liệu float (số thực dấu chấm động).

Cú pháp

float(x)  # x: int, float, string

Quy tắc chuỗi hợp lệ

  • Chỉ chứa chữ số, dấu chấm, dấu +/-, e/E (scientific notation)
  • Có thể có khoảng trắng đầu/cuối (bỏ qua)
  • Chuỗi đặc biệt: "nan", "inf", "infinity" (không phân biệt hoa/thường)

Ví dụ chuyển đổi

n = 89
print(type(n))        # 
f = float(n)
print(type(f))        # 

print(float(7))       # 7.0
print(float(-21.6))   # -21.6
print(float("NaN"))   # nan
print(float("InF"))   # inf
print(float("  3.14  "))  # 3.14 (bỏ qua space)

Kết quả



7.0
-21.6
nan
inf
3.14

Xử lý lỗi: Chuỗi không phải số

try:
    print(float("Tutorials"))
except ValueError as e:
    print(f"Lỗi: {e}")

Kết quả

Lỗi: could not convert string to float: 'Tutorials'

Ứng dụng: Đọc input an toàn

def safe_float_input(prompt):
    while True:
        try:
            return float(input(prompt))
        except ValueError:
            print("Vui lòng nhập số hợp lệ!")

price = safe_float_input("Nhập giá: ")
print(f"Giá: {price}")

Lưu ý

  • float có độ chính xác hữu hạn (IEEE 754 double precision ~15-17 chữ số)
  • Tính toán tiền tệ nên dùng decimal.Decimal
  • float('inf'), float('-inf'), float('nan') hữu ích cho thuật toán