python float函数字符串转换浮点数 保留位数?

>>> x = "24.412"
>>> float(x)
24.412

怎么样可以把字符串用float函数转换成浮点数并保留一定位数
如 最后结果为24.412000
位数不足后面用0补齐

UYOU
浏览 8922回答 2
2回答

料青山看我应如是

1round(float(x), 6) 你要保留结尾的0的话,不能存成float数据,float会自动去掉末尾的0 你需要保存你的结果为string或者decimal.Decimal string的话:1"%.6f" % float(x)  decimal的话:12import decimaldecimal.Decimal("%.6f" % float(x))

白衣染霜花

int函数能够(1)把符合数学格式的数字型字符串转换成整数(2)把浮点数转换成整数,但是只是简单的取整,而非四舍五入。举例:1 aa = int("124") #Correct2 print "aa = ", aa #result=1243 bb = int(123.45) #correct4 print "bb = ", bb #result=1235 cc = int("-123.45") #Error,Can't Convert to int6 print "cc = ",cc7 dd = int("34a") #Error,Can't Convert to int8 print "dd = ",dd9 ee = int("12.3") #Error,Can't Convert to int10 print ee11二、float函数将整数和字符串转换成浮点数。举例:1 aa = float("124") #Correct2 print "aa = ", aa #result = 124.03 bb = float("123.45") #Correct4 print "bb = ", bb #result = 123.455 cc = float(-123.6) #Correct6 print "cc = ",cc #result = -123.67 dd = float("-123.34") #Correct8 print "dd = ",dd #result = -123.349 ee = float('123v') #Error,Can't Convert to float10 print ee三、str函数将数字转换成字符举例:1 aa = str(123.4) #Correct2 print aa #result = '123.4'3 bb = str(-124.a) #SyntaxError: invalid syntax4 print bb5 cc = str("-123.45") #correct6 print cc #result = '-123.45'7 dd = str('ddd') #correct8 print dd #result = ddd9 ee = str(-124.3) #correct10 print ee #result = -124.3
打开App,查看更多内容
随时随地看视频慕课网APP