如何在 Python 中进行十进制到浮点数的转换?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32285927/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 11:20:26  来源:igfitidea点击:

How to do Decimal to float conversion in Python?

pythontype-conversion

提问by noobster

I need to convert a Decimalvalue to floatin Python. Is there any method available for this type conversion?

我需要将一个Decimal值转换为floatPython 中的值。有没有可用于这种类型转换的方法?

回答by Daniel

Just use float:

只需使用float

float_number = float(decimal_number)

回答by Ahsanul Haque

Just cast it to float:

只需将其投射到浮动:

 number_in_float = float(number_you_have)

回答by Amr Magdy

There is two methods:

有两种方法:

  • float_number = float ( decimal_number )
  • float_number = decimal_number * 1.0
  • float_number = float ( decimal_number )
  • float_number = decimal_number * 1.0

First one using the built in function and second one without any function, but takecare about the 1.0not 1as it should be float so the result will be float.

第一个使用内置函数,第二个没有任何函数,但要注意1.0not1因为它应该是浮点数,所以结果将是浮点数。