A.will
A.will

Reputation: 23

Converting a scientific notation string to an integer

I have a question in Python 3.7. I am opening a text file (input.txt) and creating variables from various lines of the text file. For example my text file looks as follows:

Case1
P
1.00E+02
5.

I need to create variables so that:

title = "Case1"
area = "P"
distance = 100
factor = 5

So far this is what I have:

f = open('C:\\input.txt',"r")
title = f.readline().strip()
area = f.readline().strip()
distance = f.readline().strip()
factor = f.readline().strip().strip(".")
f.close
print(title)
print(area)
print(distance)
print(factor)

which results in:

Case1
P
1.00E+02
5

How do I get the distance variable to show up as 100 instead of 1.00E+02?

I found the link below thinking it would help, but wasn't able to solve my problem from there. This is a very small segment of my larger program that was simplified, but if it works here it will work for my needs. My program needs to open a generated text file and produce another text file, so the scientific notation number will change between 1.00E-06 and 1.00E+03. The generated text file needs to have these numbers as integers (i.e. between 0.000001 and 1000). Thanks for any help!

Converting number in scientific notation to int

Upvotes: 1

Views: 3633

Answers (1)

PhilB
PhilB

Reputation: 91

The link you posted actually gives the answer, albeit in a roundabout way. int() cannot parse strings that don't already represent integers. But a scientific number is a float.

So, you need to cast it to float first to parse the string.

Try:

print(float(distance))

For numbers with more decimals (e.g your example of 1.00E-06), you can force float notation all the time. Try:

print(format(float(distance), 'f'))

If you only want a certain number of decimals, try:

print(format(float(distance), '.2f'))  

(for example)

Upvotes: 1

Related Questions