溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

float函數(shù)類型如何轉(zhuǎn)換

發(fā)布時(shí)間:2020-09-24 11:55:21 來源:億速云 閱讀:319 作者:Leah 欄目:編程語言

這期內(nèi)容當(dāng)中小編將會(huì)給大家?guī)碛嘘P(guān)float函數(shù)類型如何轉(zhuǎn)換,文章內(nèi)容豐富且以專業(yè)的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。

函數(shù)描述

float([x]) 函數(shù)將數(shù)字或數(shù)字的字符串表示形式轉(zhuǎn)換為與它等效的有符號(hào)浮點(diǎn)數(shù)。如果參數(shù)x是一個(gè)字符串(十進(jìn)制表示的數(shù)字串),數(shù)字前面可以添加符號(hào)來表示正數(shù),或負(fù)數(shù)。符號(hào)和數(shù)字之間不能出現(xiàn)空格,但是符號(hào)前面和數(shù)字后面允許出現(xiàn)空格。

如果參數(shù) x 是一個(gè)整數(shù)或是一個(gè)浮點(diǎn)數(shù),則返回與它等效的浮點(diǎn)數(shù);如果 x 超出了 float 類型的范圍,則引發(fā) OverflowError 錯(cuò)誤。

如果參數(shù) x 缺省,則返回 0.0

如果參數(shù) x 是普通的Python對(duì)象,float([x]) 返回的是調(diào)用 x.__float __() 結(jié)果。

兼容性

Python2.x

Python3.x

注意點(diǎn)

1. 這個(gè)函數(shù)有一個(gè)特別的地方,就是使用infinity或inf來表示無窮大的數(shù)。比如+inf是正無窮大,-inf是負(fù)無窮大。在這里引入了數(shù)學(xué)上的無窮大概念,那么無窮大乘以0是等于什么呢?在這里是等于nan,即not a number(不是一個(gè)數(shù)字)

2. 參數(shù)x可省略

英文文檔

Return a floating point number constructed from a number or string x.
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.

代碼實(shí)例

>>> float('+123')
123.0
>>> float('+1.23')
1.23
>>> float('   -12345\n')
-12345.0
>>> float('1e-003')
0.001
>>> float('+1E6')
1000000.0
>>> float('-Infinity')
-inf
>>> float('inf')
inf
>>> float('-inf')
-inf
>>> float('+inf')
inf
>>> float('nan')
nan
>>> float('+nan')
nan
>>> float('-nan')
nan
>>> float()
0.0

代碼實(shí)例

class C:
    def __init__(self, score):
        self.score = score
    def __float__(slef):
        return 1.0 
c = C(100)
f = float(c)
print(f)

運(yùn)行結(jié)果

1.0

上述就是小編為大家分享的float函數(shù)類型如何轉(zhuǎn)換了,如果剛好有類似的疑惑,不妨參照上述分析進(jìn)行理解。如果想知道更多相關(guān)知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI