วิธี Float เป็นส่วนหนึ่งของไลบรารีมาตรฐานของ python ซึ่งแปลงตัวเลขหรือสตริงที่มีตัวเลขเป็นประเภทข้อมูล float มีกฎดังต่อไปนี้เมื่อพิจารณาว่าสตริงถูกต้องสำหรับการแปลงเป็นทศนิยม
-
สตริงต้องมีตัวเลขเท่านั้น
-
สามารถใช้ตัวดำเนินการทางคณิตศาสตร์ระหว่างตัวเลขได้เช่นกัน
-
สตริงสามารถแสดง NaN หรือ inf
-
ช่องว่างสีขาวที่จุดเริ่มต้นและจุดสิ้นสุดจะถูกละเว้นเสมอ
ตัวอย่าง
โปรแกรมด้านล่างระบุว่าค่าที่ต่างกันจะถูกส่งกลับเมื่อใช้ฟังก์ชัน float
n = 89
print(type(n))
f = float(n)
print(type(f))
print("input",7," with float function becomes ",float(7))
print("input",-21.6," with float function becomes ",float(-21.6))
print("input NaN, with float function becomes ",float("NaN"))
print("input InF, with float function becomes ",float("InF")) ผลลัพธ์
การเรียกใช้โค้ดข้างต้นทำให้เราได้ผลลัพธ์ดังต่อไปนี้ -
<class 'int'> <class 'float'> input 7 with float function becomes 7.0 input -21.6 with float function becomes -21.6 input NaN, with float function becomes nan input InF, with float function becomes inf
การส่งกระแสข้อมูลโดยไม่มีค่าตัวเลขทำให้เกิดข้อผิดพลาด
ตัวอย่าง
print("input Tutorials, with float function becomes ",float("Tutorials")) ผลลัพธ์
การเรียกใช้โค้ดข้างต้นทำให้เราได้ผลลัพธ์ดังต่อไปนี้ -
Traceback (most recent call last):
File "C:/xxx.py", line 18, in
print("input Tutorials, with float function becomes ",float("Tutorials"))
ValueError: could not convert string to float: 'Tutorials'