Home > database >  Python Convert String to Float without Scientific Notation
Python Convert String to Float without Scientific Notation

Time:08-17

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().

CodePudding user response:

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

CodePudding user response:

As Josh Friedlander mentions you are comparing an int to a float which will always be invalid.

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...

>>> from decimal import Decimal
>>> n = float('9400108205499941468492')
>>> format(Decimal.from_float(n))
'9400108205499941388288'
>>> y = format(Decimal.from_float(n))
>>> type(y)
<class 'str'>
  • Related