[英]Python Convert String to Float without Scientific Notation
I have some code to convert string to float:我有一些代码可以将字符串转换为浮点数:
n = float('9400108205499941468492')
My unittest throws exceptions:我的单元测试抛出异常:
self.assertEqual(9400108205499941468492, n)
Expected :9400108205499941468492
Actual :9.400108205499941e+21
What should I do to disable scientific notation in float().我应该怎么做才能在 float() 中禁用科学计数法。
you can use int() instead of float and when you add 0.5 or any other float then if you want the approximate value then you use int您可以使用 int() 代替 float 并且当您添加 0.5 或任何其他浮点数时,如果您想要近似值,则使用 int
As Josh Friedlander mentions you are comparing an int to a float which will always be invalid.正如 Josh Friedlander 提到的,您将 int 与永远无效的 float 进行比较。
In order to represent a float without scientific notation you can use Decimal but this is also not going to make your comparison to an int valid...为了表示没有科学记数法的浮点数,您可以使用 Decimal 但这也不会使您与 int 的比较有效......
>>> from decimal import Decimal
>>> n = float('9400108205499941468492')
>>> format(Decimal.from_float(n))
'9400108205499941388288'
>>> y = format(Decimal.from_float(n))
>>> type(y)
<class 'str'>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.