Converting a scientific notation string to an integer - string

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

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)

Related

How to convert a String to a Float which is rounded UP to 4 decimal places

I have this string: "123,456.39213212"
I would like to to be converted to a float and rounded UP to the 4th decimal place.
According to an online tool I used I should get this number: 123456.3922
Please advise how I can do this in Groovy?
Thanks
It feels a bit hacky, but if your thousands separator is always , you can do something like this:
import java.math.RoundingMode
def input = "123,456.39213212"
def output = new BigDecimal(input.replaceAll(",", "")).setScale(4, RoundingMode.UP)
​Output:
123456.3922
Key parts are:
Replacing the comma with "" to have the string in a format that BigDecimal can work with and
Setting the scale to 4 using RoundingMode.UP (note: depending on your requirements regarding negative numbers you may want to use RoundingMode.CEILING instead)

Python: How can read as float numbers a series of strings from a text file?

I'm trying to read from a text file line by line a series of strings like these:
11,52.15384615384615,52.84615384615385,14.0,45.15384615384615,39.76923076923077
10,27.09090909090909,54.81818181818182,64.36363636363636,65.54545454545455,21.90909090909091
(The first number is an integer used as index), and what I would like to get are float numbers such as
11, 52.15, 52.85, 14.00, 45.15, 39.77
10, 27.09, 54.82, 64.36, 65,54, 21.91
How can I convert these strings to a list of numbers?
Sounds like you are trying to get a list of floats together from a text file. You can use a dict to map the index you mention to the list of floats. Then just open the file, read line by line, use split(',') to split the string into a list of strings. Then grab the first integer as you index, use list slice to look the rest of the strings and convert/round them and add them to a new list which you can later assign to your index.
It's easier to read the code probably than it is to explain it.
my_float_dict = dict()
with open('my_float_strings.txt','r') as f:
for line in f:
string_list = line.split(',')
index = int(string_list[0])
line_float_list = []
for field in string_list[1:]:
line_float_list.append(round(float(field),2))
my_float_dict[index] = line_float_list
print my_float_dict
From your example I think this is what you are looking for.
Below the string s is converted to a float then rounded to 2 decimal points
>>>s='51.843256'
>>>round(float(s), 2)
51.84

Converting between a number to a string without num2str

For example, input is a=5678. How do you make b='5678'? (b is a String).
Not allowed to use str2num or any casting.
Is it possible to use log10? (I know how to do the reverse action).
[This is how I did the opposite (from string to num):
s = input('Enter a number: ','s');
x = sum(10.^(length(s-'0')-1:-1:0).*(s-'0'));
This looks like homework, so first here are some hints:
log10 may be useful to determine the number of digits.
mod can help to obtain each digit.
From your code for the reverse action: using successive powers of 10, as well as +'0' / -'0' to convert between digits and ASCII codes, may also be of help here.
And here's a possible approach using these hints (hover the mouse to find out):
b = char(mod(floor(a./10.^((ceil(log10(a))-1):-1:0)),10) + '0'):

Converting lists of digits stored as strings into integers Python 2.7

Among other things, my project requires the retrieval of distance information from file, converting the data into integers, then adding them to a 128 x 128 matrix.
I am at an impasse while reading the data from line.
I retrieve it with:
distances = []
with open(filename, 'r') as f:
for line in f:
if line[0].isdigit():
distances.extend(line.splitlines())`
This produces a list of strings.
while
int(distances) #does not work
int(distances[0]) # produces the correct integer when called through console
However, the spaces foobar the procedure later on.
An example of list:
['966']['966', '1513' 2410'] # the distance list increases with each additional city. The first item is actually the distance of the second city from the first. The second item is the distance of the third city from the first two.
int(distances[0]) #returns 966 in console. A happy integer for the matrix. However:
int(distances[1]) # returns:
Traceback (most recent call last):
File "", line 1, in
ValueError: invalid literal for int() with base 10: '1513 2410'
I have a slight preference for more pythonic solutions, like list comprehension and the like, but in reality- any and all help is greatly appreciated.
Thank you for your time.
All the information you get from a file is a string at first. You have to parse the information and convert it to different types and formats in your program.
int(distances) does not work because, as you have observed, distances is a list of strings. You cannot convert an entire list to an integer. (What would be the correct answer?)
int(distances[0]) works because you are converting only the first string to an integer, and the string represents an integer so the conversion works.
int(distances[1]) doesn't work because, for some reason, there is no comma between the 2nd and 3rd element of your list, so it is implicitly concatenated to the string 1513 2410. This cannot be converted to an integer because it has a space.
There are a few different solutions that might work for you, but here are a couple of obvious ones for your use case:
distance.extend([int(elem) for elem in line.split()])
This will only work if you are certain every element of the list returned by line.split() can undergo this conversion. You can also do the whole distance list later all at once:
distance = [int(d) for d in distance]
or
distance = map(int, distance)
You should try a few solutions out and implement the one you feel gives you the best combination of working correctly and readability.
My guess is you want to split on all whitespace, rather than newlines. If the file's not large, just read it all in:
distances = map(int, open('file').read().split())
If some of the values aren't numeric:
distances = (int(word) for word in open('file').read().split() if word.isdigit())
If the file is very large, use a generator to avoid reading it all at once:
import itertools
with open('file') as dists:
distances = itertools.chain.from_iterable((int(word) for word in line.split()) for line in dists)

MATLAB: Convert string to number and then back to string

There is a string containing a number in an arbitrary format (e.g., 12, -34.5, and 6.78e-9). The goal is to convert this string into the corresponding number and then convert this number back to a string such that (a) the precision given in the original string is preserved, and (b) the resulting string has an adequate format (probably, the most adequate format is the format of the original string). I thought the problem could be easily solved using str2num and num2str; however, in some cases, MATLAB seems to be mangling the final result as shown below:
>> a = '1e23'
a =
1e23
>> b = str2num(a)
b =
1.0000e+23
>> c = num2str(b)
c =
9.999999999999999e+22
One solution is to use a general format string:
>> c = num2str(b, '%e')
c =
1.000000e+23
However, in this case, the output looks rather cumbersome for numbers of small orders:
>> d = num2str(1, '%e')
d =
1.000000e+00
In most cases, num2str without additional parameters does a pretty good job resulting in a nicely formatted string. The question is: Is there a way to eliminate the 9.999999999999999e+22 problem?
Thank you!
Regards,
Ivan
In general the representation of one input string does not contain enough information to determine the format. Hence (assuming you want to output slightly different numbers and cannot simply store the number in string format), the simplest way would be to try and find a format that you like.
Judging from your comments, I think you will be happy with:
format short g
For large numbers it will give:
x = num2str(1.0000e+23);str2num(x)
ans =
1e+23
And for small numbers:
x = num2str(1);str2num(x)
ans =
1

Resources