Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

float() ใน Python

เมธอด Float เป็นส่วนหนึ่งของไลบรารีมาตรฐานของ Python ซึ่งแปลงตัวเลขหรือสตริงที่มีตัวเลขให้เป็นชนิดข้อมูล float (ทศนิยม) มีกฎดังต่อไปนี้เมื่อสตริงถูกพิจารณาว่าถูกต้องสำหรับการแปลงเป็น float:

  • สตริงต้องมีเฉพาะตัวเลขเท่านั้น
  • ตัวดำเนินการทางคณิตศาสตร์ระหว่างตัวเลขก็สามารถใช้ได้
  • สตริงสามารถแทน NaN หรือ inf ได้
  • ช่องว่าง (white spaces) ที่จุดเริ่มต้นและจุดสิ้นสุดจะถูกละเว้นเสมอ

ตัวอย่าง

โปรแกรมด้านล่างบ่งชี้ว่าค่าต่างๆ จะถูกคืนเมื่อใช้ฟังก์ชัน 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'