Python內置函數(22)——float

英文文檔:html

class float([x]) shell

Return a floating point number constructed from a number or string x.ide

If the argument is a string, it should contain a decimal number, optionally preceded by a sign, and optionally embedded in whitespace. The optional sign may be '+' or '-'; a '+' sign has no effect on the value produced. The argument may also be a string representing a NaN (not-a-number), or a positive or negative infinity. More precisely, the input must conform to the following grammar after leading and trailing whitespace characters are removed:函數

sign           ::=  "+" | "-"
infinity       ::=  "Infinity" | "inf"
nan            ::=  "nan"
numeric_value  ::=   |  | 
numeric_string ::=  [] 
floatnumberinfinitynansignnumeric_value

Here floatnumber is the form of a Python floating-point literal, described in Floating point literals. Case is not significant, so, for example, 「inf」, 「Inf」, 「INFINITY」 and 「iNfINity」 are all acceptable spellings for positive infinity.spa

Otherwise, if the argument is an integer or a floating point number, a floating point number with the same value (within Python’s floating point precision) is returned. If the argument is outside the range of a Python float, an OverflowError will be raised.code

For a general Python object x, float(x) delegates to x.__float__().orm

If no argument is given, 0.0 is returned.htm

 

說明:對象

  1. 函數功能將一個數值或者字符轉換成浮點型數值。blog

>>> float(3)
3.0
>>> float('3')
3.0

  2. 不提供參數的時候,返回0.0。

>>> float()
0.0

  3. 字符串必須能正確轉換成浮點型數值的,不然報錯。

>>> float('3.14.15926')
Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    float('3.14.15926')
ValueError: could not convert string to float: '3.14.15926'

  4. 字符串中容許出現「+」、「-」兩個符號,兩個符號和數字之間不能出現空格,可是符號前面和數字後面容許出現空格。

>>> float('+3.14') #帶正號
3.14
>>> float('-3.14') #帶負號
-3.14
>>> float('  -3.14  ') #正負號前、數字後能夠有空格
-3.14
>>> float('- 3.14') #正負號與數字間不能夠有空格
Traceback (most recent call last):
  File "<pyshell#8>", line 1, in <module>
    float('- 3.14')
ValueError: could not convert string to float: '- 3.14'

  5. 有幾個特殊的字符串能正確轉換,"Infinity"或者「inf」(不區分大小寫),能正確轉換,表示無窮大,能夠和「+」、「-」一塊兒使用;「nan」也能正確轉換,表示沒有值。

>>> float('Infinity')
inf
>>> float('inf')
inf

>>> float('inFinIty') #不區分大小寫
inf

>>> float('+inFinIty') #正無窮
inf
>>> float('-inFinIty') #負無窮
-inf

>>> float('nan') #沒有值
nan

  6. 定義的對象若是要被float函數正確轉換成浮點數,須要定義__float__函數。

>>> class X:
    def __init__(self,score):
        self.score = score

>>> x = X(9.7)
>>> float(x) #不能轉換
Traceback (most recent call last):
  File "<pyshell#20>", line 1, in <module>
    float(x)
TypeError: float() argument must be a string or a number, not 'X'


>>> class X: #從新定義類,加入__float__方法
    def __init__(self,score):
        self.score = score
    def __float__(self):
        return self.score

>>> x = X(9.7)
>>> float(x) #能夠轉換
9.7
相關文章
相關標籤/搜索