Convert Scientific Notation to String - python

When I load xlsx file. I have a number IBAN with scientific notation.
For example:
7.810500161524e+25
This number should be:
78105001615240000000000000
I want to convert this number to string, but I get result:
'7.810500161524e+25'
I thought if I converted to int and then to string it would be the correct result, but again I get wrong result:
'78105001615239996483043328'
Anyone have any idea?

You can convert your string '7.810500161524e+25' to a decimal.Decimal number without altering its precision at all the way you will if you convert it to a floating point value. Then (if necessary) you can convert the decimal value to an integer or a string.
import decimal
scientific_notation = '7.810500161524e+25'
decimal_number = decimal.Decimal(scientific_notation) # Decimal('7.810500161524E+25')
int_number = int(decimal_number) # 78105001615240000000000000
fixed_point_string = format(decimal_number, 'f') # '78105001615240000000000000'

Related

Convert float to string without losing information - Python

I am trying to use geopy to reverse fetch location deatils based off of location coordinates. Right now I have Lat and Long in two different columns in pandas and both are of float type. Now to use locator.reverse(''), the input must be a string. And when I try to cast float to string, I am losing some information in the form of changed numbers like
df.Lat[0] = 42.279971
df.Lat.astype('str')
df.Lat[0] = 42.27997063
Why is it rounding off? I need exactly the float number as it is given to me?
Thanks for helping!
In your case here, you are not losing precision by converting float to string. Instead, it is because Pandas defaults to show only 6 decimal points for float numbers. When you convert it to string, this output default is not applied.
You can test it by e.g. to set the default float precision to 8:
pd.set_option("precision", 8)
Then, you will see that before the string conversion, the values is already in that precision already.
I am not sure it can help or not, it convert all cells in dataframe into string
df = df.applymap(lambda x: str(x))
Use repr() to convert float to string without losing precision:
Try:
df.Lat = df.Lat.apply(lambda x: repr(x))
Or
df.Lat = df.Lat.apply(repr)

Python - Converting String Numbers To Float

I want to convert string numbers on a list to float numbers
and i can't do it, so i need some help.
num = '0.00003533'
print('{:f}'.format(float(num)))
formatting it without decimals, only returns a float of 0.000035, i need the entire string in a float.
print('{:8f}'.format(float(num)))
adding the exact decimal works, but the numbers in the list with decimals varies greatly, so i can't manually add it everytime, how could i automatically add the correct decimal number inside the format?
something like '{':exactdecimalf'} exactdecinal being a variable.
i'm using a module that requires float, which is why i can't print it directly from the string format.
Use this
from decimal import Decimal
num = '0.00003533'
print(Decimal(num)) #0.00003533
if you want to print as string
print ('{:f}'.format(Decimal(num)))
Maybe double precision will suit you.
from decimal import Decimal
print ('{:f}'.format(Decimal(num)))
You can split the string and take the length of the last part with
len(num.split(".")[1])
Then use that as the number of decimals.

How to convert exponential value to string format in python?

I'm doing some calculations which give very small decimal numbers for example, 0.0000082
When I'm saving it in a variable, it changes into exponent form. I need the result as a string in the end. So, converting the result using str() is not possible because it keeps the e in the string.
I need the string to have exactly 8 decimal places. Is there any way to do this while keeping the 8 digit precision intact?
Another example: 5.8e-06 should be converted to '0.00000580' The trailing zero in the final string is not important.
I need the string to be used elsewhere. So, this shouldn't be done in the print() function.
The exponential notation is not an inherent property of the number (which is stored as a binary floating point value). It's just the default representation when converting the number to a string with str. You can specify your own formatting options if you convert the number to a string using the format function. Try something like this:
format(5.8e-06, '.8f')
The 8 in the format specifier tells it to use eight digits of precision, while the f requests it to be written as a plain decimal without exponential notation. You can read more about the format notations in the documentation.
Just another idea:
'{0:.7f}'.format(0.0000082)
you can try with :
import decimal
print(str(decimal.Decimal(5.8e-06))[:10])
>>> 0.00000580
print ("{:.6f}".format(1e-4))
will print out
0.000100
You could use print:
>>> number = 1e-08
>>> number
1e-08
>>>print("{:.12f}".format(float(number)))
0.000000010000
or You could convert number and store it in string:
>>> str1 = "{:.12f}".format(float(number))
>>> str1
'0.000000010000'

How to get rid of quotes in a json string resulting from converting scientific notation to exact value

I have a list of dictionary items that I will iterate through to update into a dictionary. That dictionary will be converted to a json string which will get inserted into an SQL database. My problem is that some of those values in the dictionary items can be very small (or large), and thus Python automatically puts it in scientific notation.
For example, I have this dictionary: {"Name": {"Key1": "0.000006", "Key2": "0.0000000001"}}. I've been able to convert scientific notation to an exact value string using the function that I created below. But now I have to keep it as a string because as soon as I cast float() on that string, it goes back to scientific notation. So then when I use json.dumps() to put the dictionary into a json string, it creates unnecessary quotes around those string-casted float values: "{"Name": {"Key1": "0.000006", "Key2": "0.0000000001"}}". How do I get rid of those quotes?
def format_float(self, value):
value_string = str(value)
# Anything smaller than or equal to 1e-5 will get converted to scientific notation
# If the value is in scientific notation
if 1e-323 <= abs(value) <= 1e-5:
# Split the string by the exponent sign
split_value_string = value_string.split("e-")
# Get the exponential
exponential = int(split_value_string[1])
# If there is a decimal, there could be digits after the decimal
if "." in split_value_string[0]:
precision = len(split_value_string[0].split(".")[1])
else:
precision = 0
f = "%.*f" % (exponential + precision, value)
elif value == float("inf") or value == float("-inf"):
return value
# Not in scientific notation
else:
if "." in value_string:
precision = len(value_string.split(".")[1])
else:
precision = 0
f = "%.*f" % (precision, value)
# No decimal
if "." not in f:
f += ".0"
p = f.partition(".")
s = "".join((p[0], p[1], p[2][0], p[2][1:].rstrip("0"))) # Get rid of the excess 0s
return s
float() shouldn't be putting anything in scientific notation. It's just that when python prints a float that's really long, it prints it in scientific notation. try using json.dumps() while keeping the values as float, it should give you what you want.
edit: let me rephrase. json.dumps() will give you valid json. the json specification allows for floats to be given as scientific notation, so the fact that it's in scientific notation shouldn't be a problem. That is, if you load what has been dumped, it will give you a float, which you can do math on as you would expect. e.g.: type(json.loads(json.dumps({'lol':1e-8}))['lol']) gives me float
If you REALLY need to have the json not have scientific notation in it, for example if the thing that will read the json is not standards-compliant, then you can use json.dumps() to dump it as a string, then use re.sub() to replace the numbers.
precision = 10
re.sub('\d+e-?\d+',lambda x: '%.*f'%(precision,float(x.group())),json.dumps({'lol':1e-8}))
gives me
'{"lol": 0.0000000100}'

representing large number in python

I am getting a large value as a string as follows
s='1234567'
d='12345678912'
I want to do arithmetic as (100/d)*s
To do this, I need to convert the strings to appropriate large values. What would be the way to represent them as a number?
Just convert them using float. Python takes care of creating appropriately large representation. You can read more about Numerals here.
s='1234567'
d='12345678912'
(100/float(d))*float(s)
You could convert them using int, but as #GamesBrainiac pointed, that will work only in Python3; in Python2 it will most of the time give you 0 as result.
(100/int(d))*int(s)
If s and d are large e.g., thousands of digits then you could use fractions module to find the fraction:
from fractions import Fraction
s = int('1234567')
d = int('12345678912')
result = Fraction(100, d) * s
print(result)
# -> 30864175/3086419728
float has finite precision; It won't work for very large/small numbers.

Categories

Resources